title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MongoDB – Inequality Operator $ne
27 Mar, 2020 MongoDB provides different types of comparison operators and inequality or not equals operator( $ne ) is one of them. This operator is used to select those documents where the value of the field does not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement. Syntax: {field: {$ne: value}} In the following examples, we are working with: Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs. Example #1:In this example, we are selecting those documents where the value of the experienceYear field is not equal to 2. Example #2:In this example, we are selecting only those documents where the last name of the employees is not Goyal. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation. Example #3:In this example, we are selecting those documents where the points array is not equal to the specified array. Example #4:In this example, we are updating the salary to 55000 of those employees whose department is not HR. Or in other words, set the value of the salary field to 55000 of those documents whose department field value is not equal to HR. MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Fuzzy Logic | Introduction Mounting a Volume Inside Docker Container
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2020" }, { "code": null, "e": 422, "s": 28, "text": "MongoDB provides different types of comparison operators and inequality or not equals operator( $ne ) is one of them. This operator is used to select those documents where the value of the field does not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement." }, { "code": null, "e": 430, "s": 422, "text": "Syntax:" }, { "code": null, "e": 452, "s": 430, "text": "{field: {$ne: value}}" }, { "code": null, "e": 500, "s": 452, "text": "In the following examples, we are working with:" }, { "code": null, "e": 644, "s": 500, "text": "Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs." }, { "code": null, "e": 768, "s": 644, "text": "Example #1:In this example, we are selecting those documents where the value of the experienceYear field is not equal to 2." }, { "code": null, "e": 1009, "s": 768, "text": " Example #2:In this example, we are selecting only those documents where the last name of the employees is not Goyal. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation." }, { "code": null, "e": 1131, "s": 1009, "text": " Example #3:In this example, we are selecting those documents where the points array is not equal to the specified array." }, { "code": null, "e": 1373, "s": 1131, "text": " Example #4:In this example, we are updating the salary to 55000 of those employees whose department is not HR. Or in other words, set the value of the salary field to 55000 of those documents whose department field value is not equal to HR." }, { "code": null, "e": 1381, "s": 1373, "text": "MongoDB" }, { "code": null, "e": 1407, "s": 1381, "text": "Advanced Computer Subject" }, { "code": null, "e": 1505, "s": 1407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1541, "s": 1505, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 1565, "s": 1541, "text": "Markov Decision Process" }, { "code": null, "e": 1601, "s": 1565, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 1645, "s": 1601, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 1680, "s": 1645, "text": "Getting Started with System Design" }, { "code": null, "e": 1721, "s": 1680, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 1769, "s": 1721, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 1810, "s": 1769, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 1837, "s": 1810, "text": "Fuzzy Logic | Introduction" } ]
Python - Data Science Tutorial
Data is the new Oil. This statement shows how every modern IT system is driven by capturing, storing and analysing data for various needs. Be it about making decision for business, forecasting weather, studying protein structures in biology or designing a marketing campaign. All of these scenarios involve a multidisciplinary approach of using mathematical models, statistics, graphs, databases and of course the business or scientific logic behind the data analysis. So we need a programming language which can cater to all these diverse needs of data science. Python shines bright as one such language as it has numerous libraries and built in features which makes it easy to tackle the needs of Data science. In this tutorial we will cover these the various techniques used in data science using the Python programming language. This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data science in simple and easy steps using Python as a programming language. Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python IDE and execution of Python programs. If you are completely new to python then please refer our Python tutorial to get a sound understanding of the language. For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning. Try following example using Try it option available at the top right corner of the below sample code box #!/usr/bin/python print "Hello, Python!"
[ { "code": null, "e": 3376, "s": 2663, "text": "Data is the new Oil. This statement shows how every modern IT system is driven by capturing, storing and analysing data for various needs. Be it about making decision for business, forecasting weather, studying protein structures in biology or designing a marketing campaign. All of these scenarios involve a multidisciplinary approach of using mathematical models, statistics, graphs, databases and of course the business or scientific logic behind the data analysis. So we need a programming language which can cater to all these diverse needs of data science. Python shines bright as one such language as it has numerous libraries and built in features which makes it easy to tackle the needs of Data science." }, { "code": null, "e": 3496, "s": 3376, "text": "In this tutorial we will cover these the various techniques used in data science using the Python programming language." }, { "code": null, "e": 3690, "s": 3496, "text": "This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data science in simple and easy steps using Python as a programming language." }, { "code": null, "e": 3988, "s": 3690, "text": "Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python IDE and execution of Python programs.\nIf you are completely new to python then please refer our Python tutorial to get a sound understanding of the language." }, { "code": null, "e": 4113, "s": 3988, "text": "For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning." }, { "code": null, "e": 4219, "s": 4113, "text": "Try following example using Try it option available at the top right corner of the below sample code box " } ]
Java and Multiple Inheritance
17 Dec, 2021 Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority. Note: Java doesn’t support Multiple Inheritance Example 1: Java // Java Program to Illustrate Unsupportance of// Multiple Inheritance // Importing input output classesimport java.io.*; // Class 1// First Parent classclass Parent1 { // Method inside first parent class void fun() { // Print statement if this method is called System.out.println("Parent1"); }} // Class 2// Second Parent Classclass Parent2 { // Method inside first parent class void fun() { // Print statement if this method is called System.out.println("Parent2"); }} // Class 3// Trying to be child of both the classesclass Test extends Parent1, Parent2 { // Main driver method public static void main(String args[]) { // Creating object of class in main() method Test t = new Test(); // Trying to call above functions of class where // Error is thrown as this class is inheriting // multiple classes t.fun(); }} Output: Compilation error is thrown Conclusion: As depicted from code above, on calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method. Example 2: GrandParent / \ / \ Parent1 Parent2 \ / \ / Test The code is as follows Java // Java Program to Illustrate Unsupportance of// Multiple Inheritance// Diamond Problem Similar Scenario // Importing input output classesimport java.io.*; // Class 1// A Grand parent class in diamondclass GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println("Grandparent"); }} // Class 2// First Parent classclass Parent1 extends GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println("Parent1"); }} // Class 3// Second Parent Classclass Parent2 extends GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println("Parent2"); }} // Class 4// Inheriting from multiple classesclass Test extends Parent1, Parent2 { // Main driver method public static void main(String args[]) { // Creating object of this class i main() method Test t = new Test(); // Now calling fun() method from its parent classes // which will throw compilation error t.fun(); }} Output: Again it throws compiler error when run() method as multiple inheritances cause a diamond problem when allowed in other languages like C++. From the code, we see that: On calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Child’s fun() method. Therefore, in order to avoid such complications, Java does not support multiple inheritances of classes. Multiple inheritance is not supported by Java using classes, handling the complexity that causes due to multiple inheritances is very complex. It creates problems during various operations like casting, constructor chaining, etc, and the above all reason is that there are very few scenarios on which we actually need multiple inheritances, so better to omit it for keeping things simple and straightforward. How are the above problems handled for Default Methods and Interfaces? Java 8 supports default methods where interfaces can provide a default implementation of methods. And a class can implement two or more interfaces. In case both the implemented interfaces contain default methods with the same method signature, the implementing class should explicitly specify which default method is to be used, or it should override the default method. Example 3: Java // Java program to demonstrate Multiple Inheritance// through default methods // Interface 1interface PI1 { // Default method default void show() { // Print statement if method is called // from interface 1 System.out.println("Default PI1"); }} // Interface 2interface PI2 { // Default method default void show() { // Print statement if method is called // from interface 2 System.out.println("Default PI2"); }} // Main class// Implementation class codeclass TestClass implements PI1, PI2 { // Overriding default show method public void show() { // Using super keyword to call the show // method of PI1 interface PI1.super.show(); // Using super keyword to call the show // method of PI2 interface PI2.super.show(); } // Mai driver method public static void main(String args[]) { // Creating object of this class in main() method TestClass d = new TestClass(); d.show(); }} Default PI1 Default PI2 Note: If we remove the implementation of default method from “TestClass”, we get a compiler error. If there is a diamond through interfaces, then there is no issue if none of the middle interfaces provide implementation of root interface. If they provide implementation, then implementation can be accessed as above using super keyword. Example 4: Java // Java program to demonstrate How Diamond Problem// Is Handled in case of Default Methods // Interface 1interface GPI { // Default method default void show() { // Print statement System.out.println("Default GPI"); }} // Interface 2// Extending the above interfaceinterface PI1 extends GPI {} // Interface 3// Extending the above interfaceinterface PI2 extends GPI {} // Main class// Implementation class codeclass TestClass implements PI1, PI2 { // Main driver method public static void main(String args[]) { // Creating object of this class // in main() method TestClass d = new TestClass(); // Now calling the function defined in interface 1 // from whom Interface 2and 3 are deriving d.show(); }} Default GPI solankimayank simranarora5sos avtarkumar719 java-inheritance Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Dec, 2021" }, { "code": null, "e": 438, "s": 54, "text": "Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority. " }, { "code": null, "e": 486, "s": 438, "text": "Note: Java doesn’t support Multiple Inheritance" }, { "code": null, "e": 497, "s": 486, "text": "Example 1:" }, { "code": null, "e": 502, "s": 497, "text": "Java" }, { "code": "// Java Program to Illustrate Unsupportance of// Multiple Inheritance // Importing input output classesimport java.io.*; // Class 1// First Parent classclass Parent1 { // Method inside first parent class void fun() { // Print statement if this method is called System.out.println(\"Parent1\"); }} // Class 2// Second Parent Classclass Parent2 { // Method inside first parent class void fun() { // Print statement if this method is called System.out.println(\"Parent2\"); }} // Class 3// Trying to be child of both the classesclass Test extends Parent1, Parent2 { // Main driver method public static void main(String args[]) { // Creating object of class in main() method Test t = new Test(); // Trying to call above functions of class where // Error is thrown as this class is inheriting // multiple classes t.fun(); }}", "e": 1365, "s": 502, "text": null }, { "code": null, "e": 1401, "s": 1365, "text": "Output: Compilation error is thrown" }, { "code": null, "e": 1581, "s": 1401, "text": "Conclusion: As depicted from code above, on calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method. " }, { "code": null, "e": 1592, "s": 1581, "text": "Example 2:" }, { "code": null, "e": 1737, "s": 1592, "text": " GrandParent\n / \\\n / \\\n Parent1 Parent2\n \\ /\n \\ /\n Test" }, { "code": null, "e": 1760, "s": 1737, "text": "The code is as follows" }, { "code": null, "e": 1765, "s": 1760, "text": "Java" }, { "code": "// Java Program to Illustrate Unsupportance of// Multiple Inheritance// Diamond Problem Similar Scenario // Importing input output classesimport java.io.*; // Class 1// A Grand parent class in diamondclass GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println(\"Grandparent\"); }} // Class 2// First Parent classclass Parent1 extends GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println(\"Parent1\"); }} // Class 3// Second Parent Classclass Parent2 extends GrandParent { void fun() { // Print statement to be executed when this method is called System.out.println(\"Parent2\"); }} // Class 4// Inheriting from multiple classesclass Test extends Parent1, Parent2 { // Main driver method public static void main(String args[]) { // Creating object of this class i main() method Test t = new Test(); // Now calling fun() method from its parent classes // which will throw compilation error t.fun(); }}", "e": 2816, "s": 1765, "text": null }, { "code": null, "e": 2825, "s": 2816, "text": "Output: " }, { "code": null, "e": 3234, "s": 2825, "text": "Again it throws compiler error when run() method as multiple inheritances cause a diamond problem when allowed in other languages like C++. From the code, we see that: On calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Child’s fun() method. Therefore, in order to avoid such complications, Java does not support multiple inheritances of classes." }, { "code": null, "e": 4087, "s": 3234, "text": "Multiple inheritance is not supported by Java using classes, handling the complexity that causes due to multiple inheritances is very complex. It creates problems during various operations like casting, constructor chaining, etc, and the above all reason is that there are very few scenarios on which we actually need multiple inheritances, so better to omit it for keeping things simple and straightforward. How are the above problems handled for Default Methods and Interfaces? Java 8 supports default methods where interfaces can provide a default implementation of methods. And a class can implement two or more interfaces. In case both the implemented interfaces contain default methods with the same method signature, the implementing class should explicitly specify which default method is to be used, or it should override the default method. " }, { "code": null, "e": 4098, "s": 4087, "text": "Example 3:" }, { "code": null, "e": 4103, "s": 4098, "text": "Java" }, { "code": "// Java program to demonstrate Multiple Inheritance// through default methods // Interface 1interface PI1 { // Default method default void show() { // Print statement if method is called // from interface 1 System.out.println(\"Default PI1\"); }} // Interface 2interface PI2 { // Default method default void show() { // Print statement if method is called // from interface 2 System.out.println(\"Default PI2\"); }} // Main class// Implementation class codeclass TestClass implements PI1, PI2 { // Overriding default show method public void show() { // Using super keyword to call the show // method of PI1 interface PI1.super.show(); // Using super keyword to call the show // method of PI2 interface PI2.super.show(); } // Mai driver method public static void main(String args[]) { // Creating object of this class in main() method TestClass d = new TestClass(); d.show(); }}", "e": 5139, "s": 4103, "text": null }, { "code": null, "e": 5163, "s": 5139, "text": "Default PI1\nDefault PI2" }, { "code": null, "e": 5500, "s": 5163, "text": "Note: If we remove the implementation of default method from “TestClass”, we get a compiler error. If there is a diamond through interfaces, then there is no issue if none of the middle interfaces provide implementation of root interface. If they provide implementation, then implementation can be accessed as above using super keyword." }, { "code": null, "e": 5511, "s": 5500, "text": "Example 4:" }, { "code": null, "e": 5516, "s": 5511, "text": "Java" }, { "code": "// Java program to demonstrate How Diamond Problem// Is Handled in case of Default Methods // Interface 1interface GPI { // Default method default void show() { // Print statement System.out.println(\"Default GPI\"); }} // Interface 2// Extending the above interfaceinterface PI1 extends GPI {} // Interface 3// Extending the above interfaceinterface PI2 extends GPI {} // Main class// Implementation class codeclass TestClass implements PI1, PI2 { // Main driver method public static void main(String args[]) { // Creating object of this class // in main() method TestClass d = new TestClass(); // Now calling the function defined in interface 1 // from whom Interface 2and 3 are deriving d.show(); }}", "e": 6302, "s": 5516, "text": null }, { "code": null, "e": 6314, "s": 6302, "text": "Default GPI" }, { "code": null, "e": 6328, "s": 6314, "text": "solankimayank" }, { "code": null, "e": 6344, "s": 6328, "text": "simranarora5sos" }, { "code": null, "e": 6358, "s": 6344, "text": "avtarkumar719" }, { "code": null, "e": 6375, "s": 6358, "text": "java-inheritance" }, { "code": null, "e": 6380, "s": 6375, "text": "Java" }, { "code": null, "e": 6399, "s": 6380, "text": "School Programming" }, { "code": null, "e": 6404, "s": 6399, "text": "Java" } ]
set_page_load_timeout driver method – Selenium Python
24 Oct, 2021 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around set_page_load_timeout driver method in Selenium. set_page_load_timeout method sets the amount of time to wait for a page load to complete before throwing an error.Syntax – driver.set_page_load_timeout(time_To_wait) Example – Now one can use set_page_load_timeout method as a driver method as below – driver.get("https://www.geeksforgeeks.org/") driver.set_page_load_timeout(30) To demonstrate, set_page_load_timeout method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.Program – Python3 # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # sets timeout to 30driver.set_page_load_timeout(30) Output – Browse r – akshaysingh98088 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2021" }, { "code": null, "e": 970, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around set_page_load_timeout driver method in Selenium. set_page_load_timeout method sets the amount of time to wait for a page load to complete before throwing an error.Syntax – " }, { "code": null, "e": 1013, "s": 970, "text": "driver.set_page_load_timeout(time_To_wait)" }, { "code": null, "e": 1100, "s": 1013, "text": "Example – Now one can use set_page_load_timeout method as a driver method as below – " }, { "code": null, "e": 1178, "s": 1100, "text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.set_page_load_timeout(30)" }, { "code": null, "e": 1343, "s": 1180, "text": "To demonstrate, set_page_load_timeout method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.Program – " }, { "code": null, "e": 1351, "s": 1343, "text": "Python3" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # sets timeout to 30driver.set_page_load_timeout(30)", "e": 1575, "s": 1351, "text": null }, { "code": null, "e": 1597, "s": 1575, "text": "Output – Browse r – " }, { "code": null, "e": 1616, "s": 1599, "text": "akshaysingh98088" }, { "code": null, "e": 1632, "s": 1616, "text": "Python-selenium" }, { "code": null, "e": 1641, "s": 1632, "text": "selenium" }, { "code": null, "e": 1648, "s": 1641, "text": "Python" }, { "code": null, "e": 1746, "s": 1648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1778, "s": 1746, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1805, "s": 1778, "text": "Python Classes and Objects" }, { "code": null, "e": 1826, "s": 1805, "text": "Python OOPs Concepts" }, { "code": null, "e": 1849, "s": 1826, "text": "Introduction To PYTHON" }, { "code": null, "e": 1905, "s": 1849, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1936, "s": 1905, "text": "Python | os.path.join() method" }, { "code": null, "e": 1978, "s": 1936, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2020, "s": 1978, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2059, "s": 2020, "text": "Python | Get unique values from a list" } ]
Zoho Interview Experience | Off-Campus January 2021
23 Jun, 2021 Hello everyone, the interview had 6 rounds, and it was completely online because of the corona lockdown. If you have applied for Zoho, all the best. Let’s get started! Round 1: Guess the output and aptitude questions (~2 hours) Find the output of 20 questions in C language (no errors in code) and 15 general quantitative aptitude questions. Be prepared in nested loops, recursion, ASCII values, typecasting between char and int, functions, #define, #typedef, structures, etc. Round 2: Pattern programming round (30 minutes) Problem: https://www.geeksforgeeks.org/mirror-image-0/ Input:n = 4 Output: 0 101 21012 3210123 After coding, we have to create a GitHub repository and share the code link to Zoho before the time runs out. And I know that this looks new and not a lot of people get this additional round. Round 3: Programming round (~4 hours) C++/Java on any code editor with screen share and video call for rounds 3 and 4. Section A: Code first then explain 1. Write a program to print a snake matrix in the following pattern without using arrays and if conditions. Input: 4 Output: 2. Write a program to find the duplicate numbers in an array and their occurrences. Store the duplicate numbers in a separate array and print the output. Input : [ 1, 2, 4, 5, 2, 1, 5, 2, 10, 22, 5 ] Output: 1 -> 2 2 -> 3 5 -> 3 Section B: Explain logic then code 1. Given a String with numbers and operators. Perform the operation on the numbers in their respective order. Operator precedence need not be considered. The input string will have the numbers followed by the operators. Input: "12345 * + - + " Result: 6 [Explanation: 1 * 2 + 3 - 4 + 5 = 6] Input: "374291 - - * + -" Result: -4 [Explanation: 3 - 7 - 4 * 2 + 9 - 1 = -4] 2. For a given number N, find the next immediate palindrome number. Input: 808 Output: 818 Input: 2133 Output: 2222 3. Write a program to implement Zeckendorf’s theorem. Definition: Zeckendorf’s theorem states that every positive integer can be represented uniquely as the sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers. Example: Input: 64 Output: 55+8+1 Input: 50 Output: 34+13+3 Round 4: Advanced Programming round (~4 hours) You are probably expecting an OOP-based application like Railway reservation, Traffic control, Lift control, etc, but instead, I got something new. An algebraic problem, just one question for 3-4 hours. Write a program to multiply two or more algebraic expressions and print the result. Examples: Input: (2x+y)*(3x-5y) Output: 6x^2-7xy-5y^2 Input: (2xy+4x^2y)*(2x^2y+6xy) Output: 28x^3y^2+8x^4y^2+12x^2y^2 Input: (2x^2y+3xy^2z-xz^3)*(5xyz+3y^2z-2z) Output: 10x3y2z+6x2y3z-4x2yz+15x2y3z2+9xy4z2-6xy2z2-5x2yz4-3xy2z4+2xz4 Round 5: Technical HR round (~90 minutes) Before we go into technical questions, there will also be general questions like what is your goal in life, about family, etc. First, they will read your resume and ask questions on that, the projects, studies. They asked if I had knowledge of SQL and asked me to design a database for a social media platform, because that was the project mentioned on my resume (It can also be done in C++/Java like with Dynamic arrays and Maps), after doing so they will ask for even more features like how to find friends of a friend for a profile, create group class, post class, etc, and all of it was asked to be done on paper and pen, then to be uploaded via phone. Round 6: General HR round (~30 minutes) Well, if you have come this far, congratulations! But if you think this round will be a piece of cake, you are mistaken. Why Zoho should hire you? Why Zoho? (Why not other companies?) Who are Zoho’s competitors? What if some multinational company offered you a better salary package right now? Which will you choose and why? Conclusion Considering all these rounds, it is clear that cracking Zoho is challenging, but with the right preparation and hard work, anything is possible! Lastly, I thank GeeksforGeeks which helped me a lot to crack this interview. Marketing Off-Campus Zoho Interview Experiences Zoho Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Google Interview Questions Google SWE Interview Experience (Google Online Coding Challenge) 2022 Write It Up: Share Your Interview Experiences TCS Digital Interview Questions Nagarro Interview Experience | On-Campus 2021 Amazon Interview Experience for SDE-1 Nagarro Interview Experience
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2021" }, { "code": null, "e": 220, "s": 52, "text": "Hello everyone, the interview had 6 rounds, and it was completely online because of the corona lockdown. If you have applied for Zoho, all the best. Let’s get started!" }, { "code": null, "e": 281, "s": 220, "text": "Round 1: Guess the output and aptitude questions (~2 hours) " }, { "code": null, "e": 530, "s": 281, "text": "Find the output of 20 questions in C language (no errors in code) and 15 general quantitative aptitude questions. Be prepared in nested loops, recursion, ASCII values, typecasting between char and int, functions, #define, #typedef, structures, etc." }, { "code": null, "e": 579, "s": 530, "text": "Round 2: Pattern programming round (30 minutes) " }, { "code": null, "e": 634, "s": 579, "text": "Problem: https://www.geeksforgeeks.org/mirror-image-0/" }, { "code": null, "e": 681, "s": 634, "text": "Input:n = 4 \nOutput:\n 0\n 101\n 21012\n3210123" }, { "code": null, "e": 874, "s": 681, "text": "After coding, we have to create a GitHub repository and share the code link to Zoho before the time runs out. And I know that this looks new and not a lot of people get this additional round. " }, { "code": null, "e": 913, "s": 874, "text": "Round 3: Programming round (~4 hours) " }, { "code": null, "e": 994, "s": 913, "text": "C++/Java on any code editor with screen share and video call for rounds 3 and 4." }, { "code": null, "e": 1029, "s": 994, "text": "Section A: Code first then explain" }, { "code": null, "e": 1137, "s": 1029, "text": "1. Write a program to print a snake matrix in the following pattern without using arrays and if conditions." }, { "code": null, "e": 1146, "s": 1137, "text": "Input: 4" }, { "code": null, "e": 1154, "s": 1146, "text": "Output:" }, { "code": null, "e": 1238, "s": 1154, "text": "2. Write a program to find the duplicate numbers in an array and their occurrences." }, { "code": null, "e": 1308, "s": 1238, "text": "Store the duplicate numbers in a separate array and print the output." }, { "code": null, "e": 1383, "s": 1308, "text": "Input : [ 1, 2, 4, 5, 2, 1, 5, 2, 10, 22, 5 ]\nOutput:\n1 -> 2\n2 -> 3\n5 -> 3" }, { "code": null, "e": 1419, "s": 1383, "text": "Section B: Explain logic then code " }, { "code": null, "e": 1639, "s": 1419, "text": "1. Given a String with numbers and operators. Perform the operation on the numbers in their respective order. Operator precedence need not be considered. The input string will have the numbers followed by the operators." }, { "code": null, "e": 1789, "s": 1639, "text": "Input: \"12345 * + - + \"\nResult: 6 [Explanation: 1 * 2 + 3 - 4 + 5 = 6]\nInput: \"374291 - - * + -\"\nResult: -4 [Explanation: 3 - 7 - 4 * 2 + 9 - 1 = -4]" }, { "code": null, "e": 1857, "s": 1789, "text": "2. For a given number N, find the next immediate palindrome number." }, { "code": null, "e": 1905, "s": 1857, "text": "Input: 808\nOutput: 818\nInput: 2133\nOutput: 2222" }, { "code": null, "e": 1959, "s": 1905, "text": "3. Write a program to implement Zeckendorf’s theorem." }, { "code": null, "e": 2191, "s": 1959, "text": "Definition: Zeckendorf’s theorem states that every positive integer can be represented uniquely as the sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers." }, { "code": null, "e": 2200, "s": 2191, "text": "Example:" }, { "code": null, "e": 2251, "s": 2200, "text": "Input: 64\nOutput: 55+8+1\nInput: 50\nOutput: 34+13+3" }, { "code": null, "e": 2299, "s": 2251, "text": "Round 4: Advanced Programming round (~4 hours) " }, { "code": null, "e": 2448, "s": 2299, "text": "You are probably expecting an OOP-based application like Railway reservation, Traffic control, Lift control, etc, but instead, I got something new. " }, { "code": null, "e": 2504, "s": 2448, "text": "An algebraic problem, just one question for 3-4 hours. " }, { "code": null, "e": 2588, "s": 2504, "text": "Write a program to multiply two or more algebraic expressions and print the result." }, { "code": null, "e": 2598, "s": 2588, "text": "Examples:" }, { "code": null, "e": 2821, "s": 2598, "text": "Input: (2x+y)*(3x-5y)\nOutput: 6x^2-7xy-5y^2\nInput: (2xy+4x^2y)*(2x^2y+6xy)\nOutput: 28x^3y^2+8x^4y^2+12x^2y^2\nInput: (2x^2y+3xy^2z-xz^3)*(5xyz+3y^2z-2z)\nOutput: 10x3y2z+6x2y3z-4x2yz+15x2y3z2+9xy4z2-6xy2z2-5x2yz4-3xy2z4+2xz4" }, { "code": null, "e": 2864, "s": 2821, "text": "Round 5: Technical HR round (~90 minutes) " }, { "code": null, "e": 2992, "s": 2864, "text": "Before we go into technical questions, there will also be general questions like what is your goal in life, about family, etc. " }, { "code": null, "e": 3076, "s": 2992, "text": "First, they will read your resume and ask questions on that, the projects, studies." }, { "code": null, "e": 3523, "s": 3076, "text": "They asked if I had knowledge of SQL and asked me to design a database for a social media platform, because that was the project mentioned on my resume (It can also be done in C++/Java like with Dynamic arrays and Maps), after doing so they will ask for even more features like how to find friends of a friend for a profile, create group class, post class, etc, and all of it was asked to be done on paper and pen, then to be uploaded via phone. " }, { "code": null, "e": 3564, "s": 3523, "text": "Round 6: General HR round (~30 minutes) " }, { "code": null, "e": 3615, "s": 3564, "text": "Well, if you have come this far, congratulations! " }, { "code": null, "e": 3687, "s": 3615, "text": "But if you think this round will be a piece of cake, you are mistaken. " }, { "code": null, "e": 3713, "s": 3687, "text": "Why Zoho should hire you?" }, { "code": null, "e": 3750, "s": 3713, "text": "Why Zoho? (Why not other companies?)" }, { "code": null, "e": 3778, "s": 3750, "text": "Who are Zoho’s competitors?" }, { "code": null, "e": 3891, "s": 3778, "text": "What if some multinational company offered you a better salary package right now? Which will you choose and why?" }, { "code": null, "e": 3902, "s": 3891, "text": "Conclusion" }, { "code": null, "e": 4125, "s": 3902, "text": "Considering all these rounds, it is clear that cracking Zoho is challenging, but with the right preparation and hard work, anything is possible! Lastly, I thank GeeksforGeeks which helped me a lot to crack this interview. " }, { "code": null, "e": 4135, "s": 4125, "text": "Marketing" }, { "code": null, "e": 4146, "s": 4135, "text": "Off-Campus" }, { "code": null, "e": 4151, "s": 4146, "text": "Zoho" }, { "code": null, "e": 4173, "s": 4151, "text": "Interview Experiences" }, { "code": null, "e": 4178, "s": 4173, "text": "Zoho" }, { "code": null, "e": 4276, "s": 4178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4314, "s": 4276, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 4370, "s": 4314, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 4443, "s": 4370, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 4470, "s": 4443, "text": "Google Interview Questions" }, { "code": null, "e": 4540, "s": 4470, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 4586, "s": 4540, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 4618, "s": 4586, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 4664, "s": 4618, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 4702, "s": 4664, "text": "Amazon Interview Experience for SDE-1" } ]
MONTHNAME() Function in MySQL
02 Dec, 2020 MONTHNAME() function in MySQL is used to find month name from the given date. It Returns 0 when MONTH part for the date is 0 or greater than 12 otherwise it returns month name between January to December. Syntax : MONTHNAME(date) Parameter : This method accepts one parameter as mentioned above and described below : date : The date or datetime from which we want to extract the month name. Returns : It returns month name from the given date. Example-1 : Finding the Current Month name Using MONTHNAME() Function. SELECT MONTHNAME(NOW()) AS Current_Month; Output : Example-2 : Finding the Month name from given datetime Using MONTHNAME() Function. SELECT MONTHNAME('2015-01-26 08:09:22') AS MONTHNAME; Output : Example-3 : Finding the Month name from given datetime Using MONTHNAME() Function when the date is NULL. SELECT MONTHNAME(NULL) AS MONTHNAME; Output : Example-4 : The MONTHNAME function can also be used to find total product sold for every month. To demonstrate create a table named. Product : CREATE TABLE Product( Product_id INT AUTO_INCREMENT, Product_name VARCHAR(100) NOT NULL, Buying_price DECIMAL(13, 2) NOT NULL, Selling_price DECIMAL(13, 2) NOT NULL, Selling_Date Date NOT NULL, PRIMARY KEY(Product_id) ); Now inserting some data to the Product table : INSERT INTO Product(Product_name, Buying_price, Selling_price, Selling_Date) VALUES ('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ), ('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ), ('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ), ('BMW X5', 5000500.00, 7006500.00, '2018-10-18' ), ('Jaguar XF', 5000000, 7507000.00, '2019-01-27' ), ('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2019-04-01' ), ('Jaguar F-PACE', 5000000.00, 7000000.00, '2019-12-26' ), ('Porsche Macan', 6500000.00, 8000000.00, '2020-04-16' ) ; So, Our table looks like : mysql> SELECT * FROM Product; +------------+-----------------------+--------------+---------------+--------------+ | Product_id | Product_name | Buying_price | Selling_price | Selling_Date | +------------+-----------------------+--------------+---------------+--------------+ | 1 | Audi Q8 | 10000000.00 | 15000000.00 | 2018-01-26 | | 2 | Volvo XC40 | 2000000.00 | 3000000.00 | 2018-04-20 | | 3 | Audi A6 | 4000000.00 | 5000000.00 | 2018-07-25 | | 4 | BMW X5 | 5000500.00 | 7006500.00 | 2018-10-18 | | 5 | Jaguar XF | 5000000.00 | 7507000.00 | 2019-01-27 | | 6 | Mercedes-Benz C-Class | 4000000.00 | 6000000.00 | 2019-04-01 | | 7 | Jaguar F-PACE | 5000000.00 | 7000000.00 | 2019-12-26 | | 8 | Porsche Macan | 6500000.00 | 8000000.00 | 2020-04-16 | +------------+-----------------------+--------------+---------------+--------------+ Now, we are going to find number of product sold per month by using MONTHNAME() function. SELECT MONTHNAME(Selling_Date) MonthName, COUNT(Product_id) Product_Sold FROM Product GROUP BY MONTHNAME(Selling_Date) ORDER BY MONTHNAME(Selling_Date); Output : +-----------+--------------+ | MonthName | Product_Sold | +-----------+--------------+ | April | 3 | | December | 1 | | January | 2 | | July | 1 | | October | 1 | +-----------+--------------+ DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 233, "s": 28, "text": "MONTHNAME() function in MySQL is used to find month name from the given date. It Returns 0 when MONTH part for the date is 0 or greater than 12 otherwise it returns month name between January to December." }, { "code": null, "e": 242, "s": 233, "text": "Syntax :" }, { "code": null, "e": 259, "s": 242, "text": "MONTHNAME(date)\n" }, { "code": null, "e": 346, "s": 259, "text": "Parameter : This method accepts one parameter as mentioned above and described below :" }, { "code": null, "e": 420, "s": 346, "text": "date : The date or datetime from which we want to extract the month name." }, { "code": null, "e": 473, "s": 420, "text": "Returns : It returns month name from the given date." }, { "code": null, "e": 544, "s": 473, "text": "Example-1 : Finding the Current Month name Using MONTHNAME() Function." }, { "code": null, "e": 587, "s": 544, "text": "SELECT MONTHNAME(NOW()) AS Current_Month;\n" }, { "code": null, "e": 596, "s": 587, "text": "Output :" }, { "code": null, "e": 679, "s": 596, "text": "Example-2 : Finding the Month name from given datetime Using MONTHNAME() Function." }, { "code": null, "e": 734, "s": 679, "text": "SELECT MONTHNAME('2015-01-26 08:09:22') AS MONTHNAME;\n" }, { "code": null, "e": 743, "s": 734, "text": "Output :" }, { "code": null, "e": 848, "s": 743, "text": "Example-3 : Finding the Month name from given datetime Using MONTHNAME() Function when the date is NULL." }, { "code": null, "e": 886, "s": 848, "text": "SELECT MONTHNAME(NULL) AS MONTHNAME;\n" }, { "code": null, "e": 895, "s": 886, "text": "Output :" }, { "code": null, "e": 1028, "s": 895, "text": "Example-4 : The MONTHNAME function can also be used to find total product sold for every month. To demonstrate create a table named." }, { "code": null, "e": 1038, "s": 1028, "text": "Product :" }, { "code": null, "e": 1274, "s": 1038, "text": "CREATE TABLE Product(\n Product_id INT AUTO_INCREMENT, \n Product_name VARCHAR(100) NOT NULL,\n Buying_price DECIMAL(13, 2) NOT NULL,\n Selling_price DECIMAL(13, 2) NOT NULL,\n Selling_Date Date NOT NULL,\n PRIMARY KEY(Product_id)\n);\n" }, { "code": null, "e": 1321, "s": 1274, "text": "Now inserting some data to the Product table :" }, { "code": null, "e": 1876, "s": 1321, "text": "INSERT INTO \n Product(Product_name, Buying_price, Selling_price, Selling_Date)\nVALUES\n ('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ),\n ('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ),\n ('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ),\n ('BMW X5', 5000500.00, 7006500.00, '2018-10-18' ),\n ('Jaguar XF', 5000000, 7507000.00, '2019-01-27' ),\n ('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2019-04-01' ),\n ('Jaguar F-PACE', 5000000.00, 7000000.00, '2019-12-26' ),\n ('Porsche Macan', 6500000.00, 8000000.00, '2020-04-16' ) ;\n" }, { "code": null, "e": 1903, "s": 1876, "text": "So, Our table looks like :" }, { "code": null, "e": 2954, "s": 1903, "text": "mysql> SELECT * FROM Product;\n+------------+-----------------------+--------------+---------------+--------------+\n| Product_id | Product_name | Buying_price | Selling_price | Selling_Date |\n+------------+-----------------------+--------------+---------------+--------------+\n| 1 | Audi Q8 | 10000000.00 | 15000000.00 | 2018-01-26 |\n| 2 | Volvo XC40 | 2000000.00 | 3000000.00 | 2018-04-20 |\n| 3 | Audi A6 | 4000000.00 | 5000000.00 | 2018-07-25 |\n| 4 | BMW X5 | 5000500.00 | 7006500.00 | 2018-10-18 |\n| 5 | Jaguar XF | 5000000.00 | 7507000.00 | 2019-01-27 |\n| 6 | Mercedes-Benz C-Class | 4000000.00 | 6000000.00 | 2019-04-01 |\n| 7 | Jaguar F-PACE | 5000000.00 | 7000000.00 | 2019-12-26 |\n| 8 | Porsche Macan | 6500000.00 | 8000000.00 | 2020-04-16 |\n+------------+-----------------------+--------------+---------------+--------------+\n" }, { "code": null, "e": 3044, "s": 2954, "text": "Now, we are going to find number of product sold per month by using MONTHNAME() function." }, { "code": null, "e": 3204, "s": 3044, "text": "SELECT MONTHNAME(Selling_Date) MonthName, \nCOUNT(Product_id) Product_Sold \nFROM Product \nGROUP BY MONTHNAME(Selling_Date) \nORDER BY MONTHNAME(Selling_Date);\n" }, { "code": null, "e": 3213, "s": 3204, "text": "Output :" }, { "code": null, "e": 3475, "s": 3213, "text": "+-----------+--------------+\n| MonthName | Product_Sold |\n+-----------+--------------+\n| April | 3 |\n| December | 1 |\n| January | 2 |\n| July | 1 |\n| October | 1 |\n+-----------+--------------+\n" }, { "code": null, "e": 3484, "s": 3475, "text": "DBMS-SQL" }, { "code": null, "e": 3490, "s": 3484, "text": "mysql" }, { "code": null, "e": 3494, "s": 3490, "text": "SQL" }, { "code": null, "e": 3498, "s": 3494, "text": "SQL" } ]
SQL | INTERSECT Clause
09 Nov, 2020 The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset returned by the INTERSECT statement will be the intersection of the data-sets of the two SELECT statements. In simple words, the INTERSECT statement will return only those rows which will be common to both of the SELECT statements. Pictorial Representation: The INTERSECT statement will return only those rows present in the red shaded region. i.e. common to both of the data-sets. Note: The number and type of fields present in the two data-sets must be same and similar. 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: SELECT column1 , column2 .... FROM table_names WHERE condition INTERSECT SELECT column1 , column2 .... FROM table_names WHERE condition Sample Tables: Customers Table: Orders Table: Sample Queries: SELECT ID, NAME, Amount, Date FROM Customers LEFT JOIN Orders ON Customers.ID = Orders.Customer_id INTERSECT SELECT ID, NAME, Amount, Date FROM Customers RIGHT JOIN Orders ON Customers.ID = Orders.Customer_id; Output: 17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribers17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ulu-P55RpDA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Harsh Agarwal. 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. Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Nov, 2020" }, { "code": null, "e": 369, "s": 52, "text": "The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset returned by the INTERSECT statement will be the intersection of the data-sets of the two SELECT statements. In simple words, the INTERSECT statement will return only those rows which will be common to both of the SELECT statements." }, { "code": null, "e": 395, "s": 369, "text": "Pictorial Representation:" }, { "code": null, "e": 519, "s": 395, "text": "The INTERSECT statement will return only those rows present in the red shaded region. i.e. common to both of the data-sets." }, { "code": null, "e": 610, "s": 519, "text": "Note: The number and type of fields present in the two data-sets must be same and similar." }, { "code": null, "e": 619, "s": 610, "text": "Chapters" }, { "code": null, "e": 646, "s": 619, "text": "descriptions off, selected" }, { "code": null, "e": 696, "s": 646, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 719, "s": 696, "text": "captions off, selected" }, { "code": null, "e": 727, "s": 719, "text": "English" }, { "code": null, "e": 751, "s": 727, "text": "This is a modal window." }, { "code": null, "e": 820, "s": 751, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 842, "s": 820, "text": "End of dialog window." }, { "code": null, "e": 850, "s": 842, "text": "Syntax:" }, { "code": null, "e": 989, "s": 850, "text": "SELECT column1 , column2 ....\nFROM table_names\nWHERE condition\n\nINTERSECT\n\nSELECT column1 , column2 ....\nFROM table_names\nWHERE condition\n" }, { "code": null, "e": 1004, "s": 989, "text": "Sample Tables:" }, { "code": null, "e": 1021, "s": 1004, "text": "Customers Table:" }, { "code": null, "e": 1035, "s": 1021, "text": "Orders Table:" }, { "code": null, "e": 1051, "s": 1035, "text": "Sample Queries:" }, { "code": null, "e": 1299, "s": 1051, "text": "SELECT ID, NAME, Amount, Date\n FROM Customers\n LEFT JOIN Orders\n ON Customers.ID = Orders.Customer_id\nINTERSECT\n SELECT ID, NAME, Amount, Date\n FROM Customers\n RIGHT JOIN Orders\n ON Customers.ID = Orders.Customer_id;\n" }, { "code": null, "e": 1307, "s": 1299, "text": "Output:" }, { "code": null, "e": 2231, "s": 1307, "text": "17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribers17. Intersect in SQL (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Ulu-P55RpDA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 2532, "s": 2231, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2657, "s": 2532, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2666, "s": 2657, "text": "Articles" } ]
Write a dictionary to a file in Python
29 Dec, 2020 Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it. Method:1 Storing Dictionary With Object Using Json Approach: Import Json Create A Dictionary in-order pass it into text file. Open file in write mode. Use json.dumps() for json string Code: Python3 import json details = {'Name': "Bob", 'Age' :28} with open('convert.txt', 'w') as convert_file: convert_file.write(json.dumps(details)) Output: Method 2: Using Loop Approach: Create a dictionary. Open a file in write mode. Here We Use For Loop With Key Value Pair Where “Name” is Key And “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs Then f.write() Function Just Write’s The Output In Form Of String “%s” Code: Python3 details={'Name' : "Alice", 'Age' : 21, 'Degree' : "Bachelor Cse", 'University' : "Northeastern Univ"} with open("myfile.txt", 'w') as f: for key, value in details.items(): f.write('%s:%s\n' % (key, value)) Output: Method:3 Without Using loads(),dumps(). Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String Python3 details = {'Name': "Bob", 'Age' :28} with open('file.txt','w') as data: data.write(str(details)) Output: Picked Python file-handling-programs python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 348, "s": 54, "text": "Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it." }, { "code": null, "e": 399, "s": 348, "text": "Method:1 Storing Dictionary With Object Using Json" }, { "code": null, "e": 409, "s": 399, "text": "Approach:" }, { "code": null, "e": 421, "s": 409, "text": "Import Json" }, { "code": null, "e": 475, "s": 421, "text": "Create A Dictionary in-order pass it into text file." }, { "code": null, "e": 500, "s": 475, "text": "Open file in write mode." }, { "code": null, "e": 533, "s": 500, "text": "Use json.dumps() for json string" }, { "code": null, "e": 539, "s": 533, "text": "Code:" }, { "code": null, "e": 547, "s": 539, "text": "Python3" }, { "code": "import json details = {'Name': \"Bob\", 'Age' :28} with open('convert.txt', 'w') as convert_file: convert_file.write(json.dumps(details))", "e": 698, "s": 547, "text": null }, { "code": null, "e": 706, "s": 698, "text": "Output:" }, { "code": null, "e": 727, "s": 706, "text": "Method 2: Using Loop" }, { "code": null, "e": 737, "s": 727, "text": "Approach:" }, { "code": null, "e": 758, "s": 737, "text": "Create a dictionary." }, { "code": null, "e": 785, "s": 758, "text": "Open a file in write mode." }, { "code": null, "e": 930, "s": 785, "text": "Here We Use For Loop With Key Value Pair Where “Name” is Key And “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs " }, { "code": null, "e": 1002, "s": 930, "text": "Then f.write() Function Just Write’s The Output In Form Of String “%s” " }, { "code": null, "e": 1008, "s": 1002, "text": "Code:" }, { "code": null, "e": 1016, "s": 1008, "text": "Python3" }, { "code": "details={'Name' : \"Alice\", 'Age' : 21, 'Degree' : \"Bachelor Cse\", 'University' : \"Northeastern Univ\"} with open(\"myfile.txt\", 'w') as f: for key, value in details.items(): f.write('%s:%s\\n' % (key, value))", "e": 1259, "s": 1016, "text": null }, { "code": null, "e": 1267, "s": 1259, "text": "Output:" }, { "code": null, "e": 1307, "s": 1267, "text": "Method:3 Without Using loads(),dumps()." }, { "code": null, "e": 1434, "s": 1307, "text": "Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String" }, { "code": null, "e": 1442, "s": 1434, "text": "Python3" }, { "code": "details = {'Name': \"Bob\", 'Age' :28} with open('file.txt','w') as data: data.write(str(details))", "e": 1547, "s": 1442, "text": null }, { "code": null, "e": 1555, "s": 1547, "text": "Output:" }, { "code": null, "e": 1562, "s": 1555, "text": "Picked" }, { "code": null, "e": 1592, "s": 1562, "text": "Python file-handling-programs" }, { "code": null, "e": 1613, "s": 1592, "text": "python-file-handling" }, { "code": null, "e": 1620, "s": 1613, "text": "Python" }, { "code": null, "e": 1718, "s": 1620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1750, "s": 1718, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1777, "s": 1750, "text": "Python Classes and Objects" }, { "code": null, "e": 1798, "s": 1777, "text": "Python OOPs Concepts" }, { "code": null, "e": 1821, "s": 1798, "text": "Introduction To PYTHON" }, { "code": null, "e": 1877, "s": 1821, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1919, "s": 1877, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1950, "s": 1919, "text": "Python | os.path.join() method" }, { "code": null, "e": 1992, "s": 1950, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2031, "s": 1992, "text": "Python | Get unique values from a list" } ]
How to Automate an Excel Sheet in Python?
11 Jul, 2022 Before you read this article and learn automation in Python....let’s watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation. You might have laughed loudly after watching this video and you surely, you might have understood the importance of automation in real life as well. Let’s come to the topic now... We all know that Python is ruling all over the world, and we also know that Python is beginner’s friendly and it’s easy to learn in comparison to other languages. One of the best things you can do with Python is Automation. Consider a scenario that you’re asked to create an account on a website for 30,000 employees. How would you feel? Surely you will be frustrated doing this task manually and repeatedly. Also, this is going to take too much time which is not a smart decision. Now just imagine the life of employees who are into the data entry jobs. Their job is to take the data from tables such as Excel or Google Sheet and insert it somewhere else. They browse different websites and magazine, they collect the data from there, and then they insert it into the database. They also need to do the calculations for the entries. Generally, the income is based on the performance in this job. More entries, higher salary (of course everyone wants a higher salary in their job). But don’t you think that it’s boring to do the same kind of stuff repeatedly? Now the question is....“How can I do it fast?”, “How can I automate my work?” Instead of doing these kinds of tasks manually, just spend an hour coding and automate these kinds of stuff to make your life easier. You can automate your tedious task by just writing fewer lines of code in Python. In this blog, we will create a small project to learn automation in Python. If you’re a beginner then you may prefer to watch some videos to learn the automation in Python and reading this blog might be a boring task for you but here we will go through step by step to explain everything in detail and to make things easier for you. It will be great if you already know the core concept of Python. We will take an example of an Excel sheet with some entries, and we will learn the automation process. We are going to write a Python program that can process thousands of spreadsheets in under a second. Excited??? Let’s get started... Processing or updating thousands of spreadsheets manually will take too much time. It may take hours, days, or even months. We will write a Python program to automate this task. We will work on a spreadsheet given in the below picture. In this spreadsheet, we have the record for all kinds of transactions, but let’s say due to an error (human error or system error), the price for the product listed in the third column is wrong. Let’s say we need to decrease the price by 10% (multiply the price by 0.9 and recalculate the value). You can do this task manually by using a mathematical formula in the fourth column but it will take too much time (maybe 1 week or two weeks) if there are thousands of records. We will write a python program to automate this process. Also, we will add a chart to it. Our python program will do this task for us in a matter of seconds. To work on this Excel sheet we are going to use a library openpyxl. Create a folder in your directory, give it a name and install the openpyxl package by executing the following command in your terminal. pip install openpyxl Now we can import this package to work on our spreadsheet. Before that add the spreadsheet in your project folder. Now create a file app.py in your folder and write down the code given below. Python import openpyxl as xlfrom openpyxl.chart import BarChart, Reference wb = xl.load_workbook('python-spreadsheet.xlsx')sheet = wb['Sheet1'] for row in range(2, sheet.max_row + 1): cell = sheet.cell(row, 3) corrected_price = float(cell.value.replace('$','')) * 0.9 corrected_price_cell = sheet.cell(row, 4) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4)chart = BarChart()chart.add_data(values)sheet.add_chart(chart, 'e2') wb.save('python-spreadsheet2.xlsx') We are going to explain the code step by step written above to understand the complete process. Step 1. To work on our spreadsheet import openpyxl package (we have used xl alias to make our code cleaner and shorter). Also, to add a chart to our spreadsheet, we need to import two classes BarChart and Reference. import openpyxl as xl from openpyxl.chart import BarChart, Reference Step 2. Now we need to load the Excel workbook python-spreadhsheet.xlsx. Write down the code given below. wb returns the object and with this object, we are accessing Sheet1 from the workbook. wb = xl.load_workbook('python-spreadsheet.xlsx') sheet = wb['Sheet1'] Step 3. To access the entries from rows 2 to 4 in the third column (entry for price column) we need to add a for loop in it. We are saving this entry in a variable cell. for row in range(2, sheet.max_row + 1): cell = sheet.cell(row, 3) Step 4. Now we need to calculate the corrected prices. So we are multiplying the values saved in the cell variable with 0.9. Once the calculation is done we need to add all the corrected prices in a new column (column 4). To add a new column we will get a reference to the cell in the given row but in the fourth column. Once the cell is created, we need to set the corrected price values in this cell (fourth column). corrected_price = float(cell.value.replace('$','')) * 0.9 corrected_price_cell = sheet.cell(row, 4) corrected_price_cell.value = corrected_price Step 5. Half of the work is done. We have calculated the updated price, and we have added that in the fourth column. Now we need to add a chart to the current sheet. To create a chart we need to select a range of values. In this project, we will select the values in the fourth column (updated prices) and we will use that in our chart (we just need a bunch of numbers to create a chart, so we have taken the example of the fourth column. This value can be anything as per requirement). We need to use the reference class to select a range of values. We are going to add five arguments to this constructor. The first argument is the sheet we are working on. The next two arguments min_row = 2, and max_row= sheet.max_row will select the cells from row 2 to row 4. To select the entries from only column fourth we need to pass another two arguments min_col=4 and max_col=4. Store the result in the variable ‘values’. values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) Step 6. Now we are ready to create a chart. We will create an instance ‘chart’ for the class BarChart. Once this is created add the values in this chart. After that add this chart to the sheet into row 2 and column 5 (e2). chart = BarChart() chart.add_data(values) sheet.add_chart(chart, 'e2') Step 7. Now we need to save all updated entries and the chart we have created in the above code. We will save this in a new file python-spreadsheet2.xlsx because we don’t’ want to accidentally overwrite the original file in case our program has a bug. Run your program and you’re good to go. A newly updated file python-spreadhsheet2.xlsx will be created for you with updated prices and charts. Below is the screenshot for the same. Step 8. Our program is complete but if you use the above code then it’s not going to automate the process of thousands of spreadsheets. This program is only relying on a specific file that is python-spreadsheet.xlsx. To make it work for several spreadsheets we will reorganize this code, and we will move the code inside a function. This function will take the name of the file as an input and it will execute the process. Below is the updated code for the same. Python import openpyxl as xlfrom openpyxl.chart import BarChart, Reference def process_workbook(filename): wb = xl.load_workbook(filename) sheet = wb['Sheet1'] for row in range(2, sheet.max_row + 1): cell = sheet.cell(row, 3) corrected_price = float(cell.value.replace('$', '')) * 0.9 corrected_price_cell = sheet.cell(row, 4) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) chart = BarChart() chart.add_data(values) sheet.add_chart(chart, 'e2') wb.save(filename) Github Link for the Code with Spreadsheet Attached: Python Automation That was just one example of using Python to automate repetitive boring tasks. But remember that automation is not just about Excel spreadsheets. There are so many things we can automate. You can search on various sites such as Github and you can automate a lot of things with Python. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jul, 2022" }, { "code": null, "e": 272, "s": 53, "text": "Before you read this article and learn automation in Python....let’s watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation." }, { "code": null, "e": 452, "s": 272, "text": "You might have laughed loudly after watching this video and you surely, you might have understood the importance of automation in real life as well. Let’s come to the topic now..." }, { "code": null, "e": 677, "s": 452, "text": "We all know that Python is ruling all over the world, and we also know that Python is beginner’s friendly and it’s easy to learn in comparison to other languages. One of the best things you can do with Python is Automation. " }, { "code": null, "e": 936, "s": 677, "text": "Consider a scenario that you’re asked to create an account on a website for 30,000 employees. How would you feel? Surely you will be frustrated doing this task manually and repeatedly. Also, this is going to take too much time which is not a smart decision. " }, { "code": null, "e": 1289, "s": 936, "text": "Now just imagine the life of employees who are into the data entry jobs. Their job is to take the data from tables such as Excel or Google Sheet and insert it somewhere else. They browse different websites and magazine, they collect the data from there, and then they insert it into the database. They also need to do the calculations for the entries. " }, { "code": null, "e": 1438, "s": 1289, "text": "Generally, the income is based on the performance in this job. More entries, higher salary (of course everyone wants a higher salary in their job). " }, { "code": null, "e": 1517, "s": 1438, "text": "But don’t you think that it’s boring to do the same kind of stuff repeatedly? " }, { "code": null, "e": 1595, "s": 1517, "text": "Now the question is....“How can I do it fast?”, “How can I automate my work?”" }, { "code": null, "e": 1812, "s": 1595, "text": "Instead of doing these kinds of tasks manually, just spend an hour coding and automate these kinds of stuff to make your life easier. You can automate your tedious task by just writing fewer lines of code in Python. " }, { "code": null, "e": 2145, "s": 1812, "text": "In this blog, we will create a small project to learn automation in Python. If you’re a beginner then you may prefer to watch some videos to learn the automation in Python and reading this blog might be a boring task for you but here we will go through step by step to explain everything in detail and to make things easier for you." }, { "code": null, "e": 2446, "s": 2145, "text": "It will be great if you already know the core concept of Python. We will take an example of an Excel sheet with some entries, and we will learn the automation process. We are going to write a Python program that can process thousands of spreadsheets in under a second. Excited??? Let’s get started..." }, { "code": null, "e": 2682, "s": 2446, "text": "Processing or updating thousands of spreadsheets manually will take too much time. It may take hours, days, or even months. We will write a Python program to automate this task. We will work on a spreadsheet given in the below picture." }, { "code": null, "e": 3157, "s": 2682, "text": "In this spreadsheet, we have the record for all kinds of transactions, but let’s say due to an error (human error or system error), the price for the product listed in the third column is wrong. Let’s say we need to decrease the price by 10% (multiply the price by 0.9 and recalculate the value). You can do this task manually by using a mathematical formula in the fourth column but it will take too much time (maybe 1 week or two weeks) if there are thousands of records. " }, { "code": null, "e": 3316, "s": 3157, "text": "We will write a python program to automate this process. Also, we will add a chart to it. Our python program will do this task for us in a matter of seconds. " }, { "code": null, "e": 3520, "s": 3316, "text": "To work on this Excel sheet we are going to use a library openpyxl. Create a folder in your directory, give it a name and install the openpyxl package by executing the following command in your terminal." }, { "code": null, "e": 3541, "s": 3520, "text": "pip install openpyxl" }, { "code": null, "e": 3733, "s": 3541, "text": "Now we can import this package to work on our spreadsheet. Before that add the spreadsheet in your project folder. Now create a file app.py in your folder and write down the code given below." }, { "code": null, "e": 3740, "s": 3733, "text": "Python" }, { "code": "import openpyxl as xlfrom openpyxl.chart import BarChart, Reference wb = xl.load_workbook('python-spreadsheet.xlsx')sheet = wb['Sheet1'] for row in range(2, sheet.max_row + 1): cell = sheet.cell(row, 3) corrected_price = float(cell.value.replace('$','')) * 0.9 corrected_price_cell = sheet.cell(row, 4) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4)chart = BarChart()chart.add_data(values)sheet.add_chart(chart, 'e2') wb.save('python-spreadsheet2.xlsx')", "e": 4290, "s": 3740, "text": null }, { "code": null, "e": 4386, "s": 4290, "text": "We are going to explain the code step by step written above to understand the complete process." }, { "code": null, "e": 4604, "s": 4386, "text": "Step 1. To work on our spreadsheet import openpyxl package (we have used xl alias to make our code cleaner and shorter). Also, to add a chart to our spreadsheet, we need to import two classes BarChart and Reference. " }, { "code": null, "e": 4673, "s": 4604, "text": "import openpyxl as xl\nfrom openpyxl.chart import BarChart, Reference" }, { "code": null, "e": 4867, "s": 4673, "text": "Step 2. Now we need to load the Excel workbook python-spreadhsheet.xlsx. Write down the code given below. wb returns the object and with this object, we are accessing Sheet1 from the workbook. " }, { "code": null, "e": 4937, "s": 4867, "text": "wb = xl.load_workbook('python-spreadsheet.xlsx')\nsheet = wb['Sheet1']" }, { "code": null, "e": 5108, "s": 4937, "text": "Step 3. To access the entries from rows 2 to 4 in the third column (entry for price column) we need to add a for loop in it. We are saving this entry in a variable cell. " }, { "code": null, "e": 5178, "s": 5108, "text": "for row in range(2, sheet.max_row + 1):\n cell = sheet.cell(row, 3)" }, { "code": null, "e": 5598, "s": 5178, "text": "Step 4. Now we need to calculate the corrected prices. So we are multiplying the values saved in the cell variable with 0.9. Once the calculation is done we need to add all the corrected prices in a new column (column 4). To add a new column we will get a reference to the cell in the given row but in the fourth column. Once the cell is created, we need to set the corrected price values in this cell (fourth column). " }, { "code": null, "e": 5743, "s": 5598, "text": "corrected_price = float(cell.value.replace('$','')) * 0.9\ncorrected_price_cell = sheet.cell(row, 4)\ncorrected_price_cell.value = corrected_price" }, { "code": null, "e": 5965, "s": 5743, "text": "Step 5. Half of the work is done. We have calculated the updated price, and we have added that in the fourth column. Now we need to add a chart to the current sheet. To create a chart we need to select a range of values. " }, { "code": null, "e": 6231, "s": 5965, "text": "In this project, we will select the values in the fourth column (updated prices) and we will use that in our chart (we just need a bunch of numbers to create a chart, so we have taken the example of the fourth column. This value can be anything as per requirement)." }, { "code": null, "e": 6660, "s": 6231, "text": "We need to use the reference class to select a range of values. We are going to add five arguments to this constructor. The first argument is the sheet we are working on. The next two arguments min_row = 2, and max_row= sheet.max_row will select the cells from row 2 to row 4. To select the entries from only column fourth we need to pass another two arguments min_col=4 and max_col=4. Store the result in the variable ‘values’." }, { "code": null, "e": 6742, "s": 6660, "text": "values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4)" }, { "code": null, "e": 6966, "s": 6742, "text": "Step 6. Now we are ready to create a chart. We will create an instance ‘chart’ for the class BarChart. Once this is created add the values in this chart. After that add this chart to the sheet into row 2 and column 5 (e2). " }, { "code": null, "e": 7037, "s": 6966, "text": "chart = BarChart()\nchart.add_data(values)\nsheet.add_chart(chart, 'e2')" }, { "code": null, "e": 7290, "s": 7037, "text": "Step 7. Now we need to save all updated entries and the chart we have created in the above code. We will save this in a new file python-spreadsheet2.xlsx because we don’t’ want to accidentally overwrite the original file in case our program has a bug. " }, { "code": null, "e": 7471, "s": 7290, "text": "Run your program and you’re good to go. A newly updated file python-spreadhsheet2.xlsx will be created for you with updated prices and charts. Below is the screenshot for the same." }, { "code": null, "e": 7689, "s": 7471, "text": "Step 8. Our program is complete but if you use the above code then it’s not going to automate the process of thousands of spreadsheets. This program is only relying on a specific file that is python-spreadsheet.xlsx. " }, { "code": null, "e": 7935, "s": 7689, "text": "To make it work for several spreadsheets we will reorganize this code, and we will move the code inside a function. This function will take the name of the file as an input and it will execute the process. Below is the updated code for the same." }, { "code": null, "e": 7942, "s": 7935, "text": "Python" }, { "code": "import openpyxl as xlfrom openpyxl.chart import BarChart, Reference def process_workbook(filename): wb = xl.load_workbook(filename) sheet = wb['Sheet1'] for row in range(2, sheet.max_row + 1): cell = sheet.cell(row, 3) corrected_price = float(cell.value.replace('$', '')) * 0.9 corrected_price_cell = sheet.cell(row, 4) corrected_price_cell.value = corrected_price values = Reference(sheet, min_row=2, max_row=sheet.max_row, min_col=4, max_col=4) chart = BarChart() chart.add_data(values) sheet.add_chart(chart, 'e2') wb.save(filename)", "e": 8537, "s": 7942, "text": null }, { "code": null, "e": 8609, "s": 8539, "text": "Github Link for the Code with Spreadsheet Attached: Python Automation" }, { "code": null, "e": 8896, "s": 8609, "text": "That was just one example of using Python to automate repetitive boring tasks. But remember that automation is not just about Excel spreadsheets. There are so many things we can automate. You can search on various sites such as Github and you can automate a lot of things with Python. " }, { "code": null, "e": 8903, "s": 8896, "text": "Python" } ]
How to count the number of times a button is clicked using JavaScript ?
29 Jan, 2021 We have given a button, and the task is to count how many times the button is clicked using JavaScript. Approach: First, we will create a HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function called. We declare a count variable and initialize it to 0. When user clicks the button, the count value increased by 1 and display it on the screen. Example: HTML <!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Increment count when button is clicked</title></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> How to count the number of times a button is clicked? </h4> <button id="btn">Click Here!</button> <p> Button Clicked <span id="display">0</span> Times </p> <script type="text/javascript"> var count = 0; var btn = document.getElementById("btn"); var disp = document.getElementById("display"); btn.onclick = function () { count++; disp.innerHTML = count; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2021" }, { "code": null, "e": 133, "s": 28, "text": "We have given a button, and the task is to count how many times the button is clicked using JavaScript. " }, { "code": null, "e": 446, "s": 133, "text": "Approach: First, we will create a HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function called. We declare a count variable and initialize it to 0. When user clicks the button, the count value increased by 1 and display it on the screen." }, { "code": null, "e": 455, "s": 446, "text": "Example:" }, { "code": null, "e": 460, "s": 455, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> <title>Increment count when button is clicked</title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> How to count the number of times a button is clicked? </h4> <button id=\"btn\">Click Here!</button> <p> Button Clicked <span id=\"display\">0</span> Times </p> <script type=\"text/javascript\"> var count = 0; var btn = document.getElementById(\"btn\"); var disp = document.getElementById(\"display\"); btn.onclick = function () { count++; disp.innerHTML = count; } </script></body> </html>", "e": 1225, "s": 460, "text": null }, { "code": null, "e": 1233, "s": 1225, "text": "Output:" }, { "code": null, "e": 1242, "s": 1233, "text": "CSS-Misc" }, { "code": null, "e": 1252, "s": 1242, "text": "HTML-Misc" }, { "code": null, "e": 1268, "s": 1252, "text": "JavaScript-Misc" }, { "code": null, "e": 1272, "s": 1268, "text": "CSS" }, { "code": null, "e": 1277, "s": 1272, "text": "HTML" }, { "code": null, "e": 1288, "s": 1277, "text": "JavaScript" }, { "code": null, "e": 1305, "s": 1288, "text": "Web Technologies" }, { "code": null, "e": 1310, "s": 1305, "text": "HTML" }, { "code": null, "e": 1408, "s": 1310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1447, "s": 1408, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1486, "s": 1447, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1525, "s": 1486, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1562, "s": 1525, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1591, "s": 1562, "text": "Form validation using jQuery" }, { "code": null, "e": 1615, "s": 1591, "text": "REST API (Introduction)" }, { "code": null, "e": 1668, "s": 1615, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1728, "s": 1668, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1789, "s": 1728, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Drop columns in DataFrame by label Names or by Index Positions
02 Jul, 2020 In this article, we will discuss how to drop columns in Pandas Dataframe by label Names or by Index Positions. Drop columns from a DataFrame can be achieved in multiple ways. Let’s create a simple dataframe with a dictionary of lists, say column names are: ‘Name’, ‘Age’, ‘Place’, ‘College’. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k'])# show the dataframedetails Output : Method 1: Drop Columns from a Dataframe using dataframe.drop() method.Example 1: Remove specific single mention column. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove column name 'Age' rslt_df = details.drop(['Age'], axis = 1)# show the dataframerslt_df Output : Example 2 : Remove specific multiple mentions columns. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove two columns name is 'Age' and # 'College' rslt_df = details.drop(['Age', 'College'], axis = 1)# show the dataframerslt_df Output : Example 3: Remove columns as based on column index. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove three columns as index base# 0, 1, 2rslt_df = details.drop(details.columns[[0, 1, 2]], axis = 1) # show the dataframerslt_df Output : Method 2: Drop Columns from a Dataframe using iloc[] and drop() method. Example: Remove all columns between a specific column to another columns(exclude) # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove all columns from column# index 1 to 3(exclude) rslt_df = details.drop(details.iloc[:, 1:3], axis = 1) # show the dataframerslt_df Output : Method 3: Drop Columns from a Dataframe using loc[] and drop() method.Example: Remove all columns between a specific column name to another columns name. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove all columns from column name # 'Name' to 'College' rslt_df = details.drop(details.loc[:, 'Name':'College'].columns, axis = 1) # show the dataframe# only indexes printrslt_df Output : Note: Different loc() and iloc() is iloc() exclude last column range element. Method 4: Drop Columns from a Dataframe by iterative way.Example: Remove specific column. # import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # loop throughout all the columnsfor column in details.columns : if column == 'Age' : # delete the column del details[column] # show the dataframedetails Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jul, 2020" }, { "code": null, "e": 203, "s": 28, "text": "In this article, we will discuss how to drop columns in Pandas Dataframe by label Names or by Index Positions. Drop columns from a DataFrame can be achieved in multiple ways." }, { "code": null, "e": 320, "s": 203, "text": "Let’s create a simple dataframe with a dictionary of lists, say column names are: ‘Name’, ‘Age’, ‘Place’, ‘College’." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k'])# show the dataframedetails", "e": 1162, "s": 320, "text": null }, { "code": null, "e": 1171, "s": 1162, "text": "Output :" }, { "code": null, "e": 1291, "s": 1171, "text": "Method 1: Drop Columns from a Dataframe using dataframe.drop() method.Example 1: Remove specific single mention column." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove column name 'Age' rslt_df = details.drop(['Age'], axis = 1)# show the dataframerslt_df", "e": 2222, "s": 1291, "text": null }, { "code": null, "e": 2231, "s": 2222, "text": "Output :" }, { "code": null, "e": 2286, "s": 2231, "text": "Example 2 : Remove specific multiple mentions columns." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove two columns name is 'Age' and # 'College' rslt_df = details.drop(['Age', 'College'], axis = 1)# show the dataframerslt_df", "e": 3253, "s": 2286, "text": null }, { "code": null, "e": 3262, "s": 3253, "text": "Output :" }, { "code": null, "e": 3314, "s": 3262, "text": "Example 3: Remove columns as based on column index." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove three columns as index base# 0, 1, 2rslt_df = details.drop(details.columns[[0, 1, 2]], axis = 1) # show the dataframerslt_df", "e": 4284, "s": 3314, "text": null }, { "code": null, "e": 4293, "s": 4284, "text": "Output :" }, { "code": null, "e": 4365, "s": 4293, "text": "Method 2: Drop Columns from a Dataframe using iloc[] and drop() method." }, { "code": null, "e": 4447, "s": 4365, "text": "Example: Remove all columns between a specific column to another columns(exclude)" }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove all columns from column# index 1 to 3(exclude) rslt_df = details.drop(details.iloc[:, 1:3], axis = 1) # show the dataframerslt_df", "e": 5424, "s": 4447, "text": null }, { "code": null, "e": 5433, "s": 5424, "text": "Output :" }, { "code": null, "e": 5587, "s": 5433, "text": "Method 3: Drop Columns from a Dataframe using loc[] and drop() method.Example: Remove all columns between a specific column name to another columns name." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # Remove all columns from column name # 'Name' to 'College' rslt_df = details.drop(details.loc[:, 'Name':'College'].columns, axis = 1) # show the dataframe# only indexes printrslt_df", "e": 6608, "s": 5587, "text": null }, { "code": null, "e": 6617, "s": 6608, "text": "Output :" }, { "code": null, "e": 6695, "s": 6617, "text": "Note: Different loc() and iloc() is iloc() exclude last column range element." }, { "code": null, "e": 6785, "s": 6695, "text": "Method 4: Drop Columns from a Dataframe by iterative way.Example: Remove specific column." }, { "code": "# import pandas library as pdimport pandas as pd # List of Tuplesstudents = [('Ankit', 22, 'Up', 'Geu'), ('Ankita', 31, 'Delhi', 'Gehu'), ('Rahul', 16, 'Tokyo', 'Abes'), ('Simran', 41, 'Delhi', 'Gehu'), ('Shaurya', 33, 'Delhi', 'Geu'), ('Harshita', 35, 'Mumbai', 'Bhu' ), ('Swapnil', 35, 'Mp', 'Geu'), ('Priya', 35, 'Uk', 'Geu'), ('Jeet', 35, 'Guj', 'Gehu'), ('Ananya', 35, 'Up', 'Bhu') ] # Create a DataFrame object from# list of tuples with columns# and indices.details = pd.DataFrame(students, columns =['Name', 'Age', 'Place', 'College'], index =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k']) # loop throughout all the columnsfor column in details.columns : if column == 'Age' : # delete the column del details[column] # show the dataframedetails", "e": 7789, "s": 6785, "text": null }, { "code": null, "e": 7798, "s": 7789, "text": "Output :" }, { "code": null, "e": 7822, "s": 7798, "text": "Python pandas-dataFrame" }, { "code": null, "e": 7836, "s": 7822, "text": "Python-pandas" }, { "code": null, "e": 7843, "s": 7836, "text": "Python" }, { "code": null, "e": 7941, "s": 7843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7959, "s": 7941, "text": "Python Dictionary" }, { "code": null, "e": 8001, "s": 7959, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8023, "s": 8001, "text": "Enumerate() in Python" }, { "code": null, "e": 8058, "s": 8023, "text": "Read a file line by line in Python" }, { "code": null, "e": 8084, "s": 8058, "text": "Python String | replace()" }, { "code": null, "e": 8116, "s": 8084, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8145, "s": 8116, "text": "*args and **kwargs in Python" }, { "code": null, "e": 8172, "s": 8145, "text": "Python Classes and Objects" }, { "code": null, "e": 8193, "s": 8172, "text": "Python OOPs Concepts" } ]
How to find index of any Currency Symbols in a given string
16 Feb, 2021 Given a string txt, the task is to find the index of currency symbols present in the given string.Examples: Input: txt = “Currency symbol of USA is $”; Output: 26 Explanation : The symbol $ is present at index 33.Input: txt = “One US Dollar($) is equal to 75.70 Indian Rupee.”; Output: 14 Naive Approach: The simplest approach to solve the problem is to do the following: Create a set of all currencies. Traverse the string and if any of the currency symbols present in the set is found in the string, print it’s index. The above approach requires Auxiliary Space for storing all the currencies in the set. Efficient Approach: The idea is to use Regular Expression to solve this problem.Create a regular expression to find currency symbol in the string as mentioned below : regex = “\\p{Sc}“;Where: {\\p{Sc} represents any currency sign.For C++ / Python, we can use regex = “\\$|\\£|\\€“Where the regex checks if any of the given currency symbol ( $, £, € ) is present in the string.Match the given string with the Regular Expression using Pattern.matcher().Print index of the character of the string for which a match is found with the given regular expression. The idea is to use Regular Expression to solve this problem. Create a regular expression to find currency symbol in the string as mentioned below : regex = “\\p{Sc}“;Where: {\\p{Sc} represents any currency sign.For C++ / Python, we can use regex = “\\$|\\£|\\€“Where the regex checks if any of the given currency symbol ( $, £, € ) is present in the string. Match the given string with the Regular Expression using Pattern.matcher(). Print index of the character of the string for which a match is found with the given regular expression. Below is the implementation of the above approach: C++ Java Python3 // C++ program to find indices of// currency symbols present in a// string using regular expression#include <iostream>#include <regex>using namespace std; // Function to find currency symbol// in a text using regular expressionvoid findCurrencySymbol(string text){ // Regex to find any currency // symbol in a text const regex pattern("\\$|\\£|\\€"); for (auto it = sregex_iterator(text.begin(), text.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch match; match = *it; cout << match.str(0) << " - " << match.position(0) << endl; } return ;} // Driver Codeint main(){ string txt = "$27 - $21.30equal to $5.70"; findCurrencySymbol(txt); return 0;} // This code is contributed by yuvraj_chandra // Java program to find indices of// currency symbols present in a// string using regular expressionimport java.util.regex.*;class GFG { // Function to find currency symbol // in a text using regular expression public static void findCurrencySymbol( String text) { // Regex to find any currency // symbol in a text String regex = "\\p{Sc}"; // Compile the ReGex Pattern p = Pattern.compile( regex); // Find match between the // given string and the // Regex using Pattern.matcher() Matcher m = p.matcher(text); // Find the next subsequence // of the input subsequence // that matches the pattern while (m.find()) { System.out.println( text.charAt(m.start()) + " - " + m.start()); } } // Driver Code public static void main(String args[]) { String txt = "$27 - $21.30" + "equal to $5.70"; findCurrencySymbol(txt); }} # Python program to find indices of# currency symbols present in a# string using regular expressionimport re # Function to find currency symbol# in a text using regular expressiondef findCurrencySymbol(text): # Regex to find any currency # symbol in a text regex = "\\$|\\£|\\€" for m in re.finditer(regex, text): print(text[m.start(0)], "-" ,m.start(0)) # Driver codetxt = "$27 - $21.30equal to $5.70"findCurrencySymbol(txt) # This code is contributed by yuvraj_chandra Output: $ - 0 $ - 6 $ - 21 Time Complexity: O(N) Auxiliary Space: O(1) yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Searching Strings Searching Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reverse the substrings of the given String according to the given Array of indices Check if the given string is shuffled substring of another string How to validate GUID (Globally Unique Identifier) using Regular Expression How to check Aadhaar number is valid or not using Regular Expression How to validate pin code of India using Regular Expression Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Feb, 2021" }, { "code": null, "e": 138, "s": 28, "text": "Given a string txt, the task is to find the index of currency symbols present in the given string.Examples: " }, { "code": null, "e": 321, "s": 138, "text": "Input: txt = “Currency symbol of USA is $”; Output: 26 Explanation : The symbol $ is present at index 33.Input: txt = “One US Dollar($) is equal to 75.70 Indian Rupee.”; Output: 14 " }, { "code": null, "e": 408, "s": 323, "text": "Naive Approach: The simplest approach to solve the problem is to do the following: " }, { "code": null, "e": 440, "s": 408, "text": "Create a set of all currencies." }, { "code": null, "e": 556, "s": 440, "text": "Traverse the string and if any of the currency symbols present in the set is found in the string, print it’s index." }, { "code": null, "e": 643, "s": 556, "text": "The above approach requires Auxiliary Space for storing all the currencies in the set." }, { "code": null, "e": 663, "s": 643, "text": "Efficient Approach:" }, { "code": null, "e": 1199, "s": 663, "text": "The idea is to use Regular Expression to solve this problem.Create a regular expression to find currency symbol in the string as mentioned below : regex = “\\\\p{Sc}“;Where: {\\\\p{Sc} represents any currency sign.For C++ / Python, we can use regex = “\\\\$|\\\\£|\\\\€“Where the regex checks if any of the given currency symbol ( $, £, € ) is present in the string.Match the given string with the Regular Expression using Pattern.matcher().Print index of the character of the string for which a match is found with the given regular expression." }, { "code": null, "e": 1260, "s": 1199, "text": "The idea is to use Regular Expression to solve this problem." }, { "code": null, "e": 1557, "s": 1260, "text": "Create a regular expression to find currency symbol in the string as mentioned below : regex = “\\\\p{Sc}“;Where: {\\\\p{Sc} represents any currency sign.For C++ / Python, we can use regex = “\\\\$|\\\\£|\\\\€“Where the regex checks if any of the given currency symbol ( $, £, € ) is present in the string." }, { "code": null, "e": 1633, "s": 1557, "text": "Match the given string with the Regular Expression using Pattern.matcher()." }, { "code": null, "e": 1738, "s": 1633, "text": "Print index of the character of the string for which a match is found with the given regular expression." }, { "code": null, "e": 1789, "s": 1738, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1793, "s": 1789, "text": "C++" }, { "code": null, "e": 1798, "s": 1793, "text": "Java" }, { "code": null, "e": 1806, "s": 1798, "text": "Python3" }, { "code": "// C++ program to find indices of// currency symbols present in a// string using regular expression#include <iostream>#include <regex>using namespace std; // Function to find currency symbol// in a text using regular expressionvoid findCurrencySymbol(string text){ // Regex to find any currency // symbol in a text const regex pattern(\"\\\\$|\\\\£|\\\\€\"); for (auto it = sregex_iterator(text.begin(), text.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch match; match = *it; cout << match.str(0) << \" - \" << match.position(0) << endl; } return ;} // Driver Codeint main(){ string txt = \"$27 - $21.30equal to $5.70\"; findCurrencySymbol(txt); return 0;} // This code is contributed by yuvraj_chandra", "e": 2656, "s": 1806, "text": null }, { "code": "// Java program to find indices of// currency symbols present in a// string using regular expressionimport java.util.regex.*;class GFG { // Function to find currency symbol // in a text using regular expression public static void findCurrencySymbol( String text) { // Regex to find any currency // symbol in a text String regex = \"\\\\p{Sc}\"; // Compile the ReGex Pattern p = Pattern.compile( regex); // Find match between the // given string and the // Regex using Pattern.matcher() Matcher m = p.matcher(text); // Find the next subsequence // of the input subsequence // that matches the pattern while (m.find()) { System.out.println( text.charAt(m.start()) + \" - \" + m.start()); } } // Driver Code public static void main(String args[]) { String txt = \"$27 - $21.30\" + \"equal to $5.70\"; findCurrencySymbol(txt); }}", "e": 3710, "s": 2656, "text": null }, { "code": "# Python program to find indices of# currency symbols present in a# string using regular expressionimport re # Function to find currency symbol# in a text using regular expressiondef findCurrencySymbol(text): # Regex to find any currency # symbol in a text regex = \"\\\\$|\\\\£|\\\\€\" for m in re.finditer(regex, text): print(text[m.start(0)], \"-\" ,m.start(0)) # Driver codetxt = \"$27 - $21.30equal to $5.70\"findCurrencySymbol(txt) # This code is contributed by yuvraj_chandra", "e": 4203, "s": 3710, "text": null }, { "code": null, "e": 4211, "s": 4203, "text": "Output:" }, { "code": null, "e": 4230, "s": 4211, "text": "$ - 0\n$ - 6\n$ - 21" }, { "code": null, "e": 4252, "s": 4230, "text": "Time Complexity: O(N)" }, { "code": null, "e": 4274, "s": 4252, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4289, "s": 4274, "text": "yuvraj_chandra" }, { "code": null, "e": 4299, "s": 4289, "text": "CPP-regex" }, { "code": null, "e": 4323, "s": 4299, "text": "java-regular-expression" }, { "code": null, "e": 4342, "s": 4323, "text": "regular-expression" }, { "code": null, "e": 4360, "s": 4342, "text": "Pattern Searching" }, { "code": null, "e": 4370, "s": 4360, "text": "Searching" }, { "code": null, "e": 4378, "s": 4370, "text": "Strings" }, { "code": null, "e": 4388, "s": 4378, "text": "Searching" }, { "code": null, "e": 4396, "s": 4388, "text": "Strings" }, { "code": null, "e": 4414, "s": 4396, "text": "Pattern Searching" }, { "code": null, "e": 4512, "s": 4414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4595, "s": 4512, "text": "Reverse the substrings of the given String according to the given Array of indices" }, { "code": null, "e": 4661, "s": 4595, "text": "Check if the given string is shuffled substring of another string" }, { "code": null, "e": 4736, "s": 4661, "text": "How to validate GUID (Globally Unique Identifier) using Regular Expression" }, { "code": null, "e": 4805, "s": 4736, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 4864, "s": 4805, "text": "How to validate pin code of India using Regular Expression" }, { "code": null, "e": 4878, "s": 4864, "text": "Binary Search" }, { "code": null, "e": 4946, "s": 4878, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 4960, "s": 4946, "text": "Linear Search" }, { "code": null, "e": 5016, "s": 4960, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Decision Tree Essentials for Every Data Scientist | by Robert Wood | Towards Data Science
Decision trees can be an incredibly useful classification method that lends very well to getting up and running with minimal code. I have used some form of decision tree to predict the likelihood a customer would churn, customer conversion, new product adoption, new feature adoption, among many other useful applications. This quick intro will serve to give you an understanding of the main benefits & limitations of using decision trees as a classification tool. I’ll also walk you through the steps to build your own decision tree and, just as important, test its performance. When it comes to classification, using a decision tree classifier is one of the easiest to use. Incredibly easy to interpret It handles missing data & outliers very well and as such requires far less up front cleaning You get to forego the categorical variable encoding as decision trees handle categoricals well! Without diving into the specifics of recursive partitioning, decision trees are able to model non-linear relationships. With all that good said they’re not always the perfect option. In the same way they can be simple, they can also be overly complicated making it nearly impossible to conceptualize or interpret. To take this idea a tad further, with a tree that is overly biased or complicated, it may be catering too well to its training data and as a result is overfit. With that said, let’s jump into it. I wont talk about cross validation or train, test split much, but will post the code below. Be sure to comment if there’s something you’d like more explanation on. First we’ll break the data into training & test sets. Also note that we’ll be using the classic titanic dataset that’s included in base R. n <- nrow(Titanic)n_train <- round(0.8 * n)set.seed(123)train_indices <- sample(1:n, n_train)train <- Titanic[train_indices, ] test <- Titanic[-train_indices, ] Now we’ll train the model using the rpart function from the rpart package. The key things to notice here is that the variable we want to predict is Survived, so we want to understand the likelihood any given individual survived according to some data. ~ can be interpreted as by; so in other words lets understand Survived by some variables. If after the ~ there is a . that means we want to use every other variable in the dataset to predict survived. Alternatively as shown below we can call out the variables we want to use explicitly. Another thing to note is that the method is class. That is because we want to create a classification tree predicting categorical outcomes, as opposed to a regression tree that would be used for numerical outcomes. And finally the data we're using to train the model is train. model <- rpart(formula = Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked, data = titanic_train, method = "class") As previously mentioned one of the things that makes a decision tree so easy to use is that it’s incredibly easy to interpret. You’re able to follow the different branches of the tree to different outcomes. rpart.plot(model) It’s a bit difficult to read there, but if you zoom in a tad, you’ll see that the first criteria if someone likely lived or died on the titanic was whether you were a male. If you were a male you move to the left branch and work down two nodes, whether you were an adult and your sibling/spouse count onboard. So if you were a single man you’re odds of survival were pretty slim. Before we break out the metrics, lets predict values for your test set. Similar to the call to train, you select the data, and type of prediction. The core difference being the model specification. test$pred <- predict(object = model, newdata = test, type = "class") There are a variety of performance evaluation metrics which will come in very handy when understanding the efficacy of your decision tree. This metric is very simple, what percentage of your predictions were correct. The confusion matrix function from caret includes this. The confusionMatrix function from the caret package is incredibly useful. For assessing classification model performance. Load up the package, and pass it your predictions & the actuals. library(caret)confusionMatrix(data = test$pred, reference = test$Survived) The first thing this function shows you is what’s called a confusion matrix. This shows you a table of how predictions and actuals lined up. So the diagonal cells where the prediction and reference are the same represents what we got correct. Counting those up 149 (106 + 43) and dividing it by the total number of records, 178; we arrive at our accuracy number of 83.4%. True positive: The cell in the quadrant where both the reference and the prediction are 1. This indicates that you predicted survival and they did in fact survive. False positive: Here you predicted positive, but you were wrong. True negative: When you predict negative, and you are correct. False negative: When you predict negative, and you are incorrect. A couple more key metrics to keep in mind are sensitivity and specificity. Sensitivity is the percentage of true records that you predicted correctly. Specificity on the other hand is to measure what portion of the actual false records you predicted correctly. Specificity is one to keep in mind when predicting on an imbalanced dataset. A very common example of this is for classifying email spam. 99% of the time it’s not spam, so if you predicted nothing was ever spam you’d have 99% accuracy, but your specificity would be 0, leading to all spam being accepted. To wrap up our discussion on decision trees, we know they can be incredibly useful because they’re extremely interpretable, there is minimal pre-processing required, they can model non-linear relationships, and they have functionality that make it easy to fix imbalanced classification problems. imbalanced datasets On the other hand, when modeling a more complicated relationship, a decision tree can be very difficult to understand and can be easily over-fit. Keep this in mind as you begin to leverage this modeling technique. I hope you enjoyed this quick lesson in decision trees. Let me know if there was something you wanted more info on or if there’s something you’d like me to cover in a different post. Happy Data Science-ing! If you enjoyed this, come check out other posts like this at datasciencelessons.com!
[ { "code": null, "e": 303, "s": 172, "text": "Decision trees can be an incredibly useful classification method that lends very well to getting up and running with minimal code." }, { "code": null, "e": 495, "s": 303, "text": "I have used some form of decision tree to predict the likelihood a customer would churn, customer conversion, new product adoption, new feature adoption, among many other useful applications." }, { "code": null, "e": 637, "s": 495, "text": "This quick intro will serve to give you an understanding of the main benefits & limitations of using decision trees as a classification tool." }, { "code": null, "e": 752, "s": 637, "text": "I’ll also walk you through the steps to build your own decision tree and, just as important, test its performance." }, { "code": null, "e": 848, "s": 752, "text": "When it comes to classification, using a decision tree classifier is one of the easiest to use." }, { "code": null, "e": 877, "s": 848, "text": "Incredibly easy to interpret" }, { "code": null, "e": 970, "s": 877, "text": "It handles missing data & outliers very well and as such requires far less up front cleaning" }, { "code": null, "e": 1066, "s": 970, "text": "You get to forego the categorical variable encoding as decision trees handle categoricals well!" }, { "code": null, "e": 1186, "s": 1066, "text": "Without diving into the specifics of recursive partitioning, decision trees are able to model non-linear relationships." }, { "code": null, "e": 1249, "s": 1186, "text": "With all that good said they’re not always the perfect option." }, { "code": null, "e": 1380, "s": 1249, "text": "In the same way they can be simple, they can also be overly complicated making it nearly impossible to conceptualize or interpret." }, { "code": null, "e": 1540, "s": 1380, "text": "To take this idea a tad further, with a tree that is overly biased or complicated, it may be catering too well to its training data and as a result is overfit." }, { "code": null, "e": 1740, "s": 1540, "text": "With that said, let’s jump into it. I wont talk about cross validation or train, test split much, but will post the code below. Be sure to comment if there’s something you’d like more explanation on." }, { "code": null, "e": 1794, "s": 1740, "text": "First we’ll break the data into training & test sets." }, { "code": null, "e": 1879, "s": 1794, "text": "Also note that we’ll be using the classic titanic dataset that’s included in base R." }, { "code": null, "e": 2041, "s": 1879, "text": "n <- nrow(Titanic)n_train <- round(0.8 * n)set.seed(123)train_indices <- sample(1:n, n_train)train <- Titanic[train_indices, ] test <- Titanic[-train_indices, ]" }, { "code": null, "e": 2580, "s": 2041, "text": "Now we’ll train the model using the rpart function from the rpart package. The key things to notice here is that the variable we want to predict is Survived, so we want to understand the likelihood any given individual survived according to some data. ~ can be interpreted as by; so in other words lets understand Survived by some variables. If after the ~ there is a . that means we want to use every other variable in the dataset to predict survived. Alternatively as shown below we can call out the variables we want to use explicitly." }, { "code": null, "e": 2857, "s": 2580, "text": "Another thing to note is that the method is class. That is because we want to create a classification tree predicting categorical outcomes, as opposed to a regression tree that would be used for numerical outcomes. And finally the data we're using to train the model is train." }, { "code": null, "e": 3010, "s": 2857, "text": "model <- rpart(formula = Survived ~ Pclass + Sex + Age + SibSp + Parch + Fare + Embarked, data = titanic_train, method = \"class\")" }, { "code": null, "e": 3217, "s": 3010, "text": "As previously mentioned one of the things that makes a decision tree so easy to use is that it’s incredibly easy to interpret. You’re able to follow the different branches of the tree to different outcomes." }, { "code": null, "e": 3235, "s": 3217, "text": "rpart.plot(model)" }, { "code": null, "e": 3615, "s": 3235, "text": "It’s a bit difficult to read there, but if you zoom in a tad, you’ll see that the first criteria if someone likely lived or died on the titanic was whether you were a male. If you were a male you move to the left branch and work down two nodes, whether you were an adult and your sibling/spouse count onboard. So if you were a single man you’re odds of survival were pretty slim." }, { "code": null, "e": 3813, "s": 3615, "text": "Before we break out the metrics, lets predict values for your test set. Similar to the call to train, you select the data, and type of prediction. The core difference being the model specification." }, { "code": null, "e": 3941, "s": 3813, "text": "test$pred <- predict(object = model, newdata = test, type = \"class\")" }, { "code": null, "e": 4080, "s": 3941, "text": "There are a variety of performance evaluation metrics which will come in very handy when understanding the efficacy of your decision tree." }, { "code": null, "e": 4214, "s": 4080, "text": "This metric is very simple, what percentage of your predictions were correct. The confusion matrix function from caret includes this." }, { "code": null, "e": 4401, "s": 4214, "text": "The confusionMatrix function from the caret package is incredibly useful. For assessing classification model performance. Load up the package, and pass it your predictions & the actuals." }, { "code": null, "e": 4498, "s": 4401, "text": "library(caret)confusionMatrix(data = test$pred, reference = test$Survived)" }, { "code": null, "e": 4870, "s": 4498, "text": "The first thing this function shows you is what’s called a confusion matrix. This shows you a table of how predictions and actuals lined up. So the diagonal cells where the prediction and reference are the same represents what we got correct. Counting those up 149 (106 + 43) and dividing it by the total number of records, 178; we arrive at our accuracy number of 83.4%." }, { "code": null, "e": 5034, "s": 4870, "text": "True positive: The cell in the quadrant where both the reference and the prediction are 1. This indicates that you predicted survival and they did in fact survive." }, { "code": null, "e": 5099, "s": 5034, "text": "False positive: Here you predicted positive, but you were wrong." }, { "code": null, "e": 5162, "s": 5099, "text": "True negative: When you predict negative, and you are correct." }, { "code": null, "e": 5228, "s": 5162, "text": "False negative: When you predict negative, and you are incorrect." }, { "code": null, "e": 5379, "s": 5228, "text": "A couple more key metrics to keep in mind are sensitivity and specificity. Sensitivity is the percentage of true records that you predicted correctly." }, { "code": null, "e": 5489, "s": 5379, "text": "Specificity on the other hand is to measure what portion of the actual false records you predicted correctly." }, { "code": null, "e": 5794, "s": 5489, "text": "Specificity is one to keep in mind when predicting on an imbalanced dataset. A very common example of this is for classifying email spam. 99% of the time it’s not spam, so if you predicted nothing was ever spam you’d have 99% accuracy, but your specificity would be 0, leading to all spam being accepted." }, { "code": null, "e": 6110, "s": 5794, "text": "To wrap up our discussion on decision trees, we know they can be incredibly useful because they’re extremely interpretable, there is minimal pre-processing required, they can model non-linear relationships, and they have functionality that make it easy to fix imbalanced classification problems. imbalanced datasets" }, { "code": null, "e": 6256, "s": 6110, "text": "On the other hand, when modeling a more complicated relationship, a decision tree can be very difficult to understand and can be easily over-fit." }, { "code": null, "e": 6324, "s": 6256, "text": "Keep this in mind as you begin to leverage this modeling technique." }, { "code": null, "e": 6507, "s": 6324, "text": "I hope you enjoyed this quick lesson in decision trees. Let me know if there was something you wanted more info on or if there’s something you’d like me to cover in a different post." } ]
OAuth 2.0 - Accessing a Protected Resource
The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired. There are two standard ways of sending credentials − Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header. Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header. They are included in the authorization header as follows − Authorization: Bearer [token-value] For Example − GET/resource/1 HTTP /1.1 Host: example.com Authorization: Bearer abc... MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner. MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner. The following table shows the concepts of accessing protected resource. It is used to get the authorization code token for accessing the owner resources in the system. The resource server includes the "WWW-Authenticate" response header field, if the protected resource request contains an invalid access token. Print Add Notes Bookmark this page
[ { "code": null, "e": 1972, "s": 1785, "text": "The client provides an access token to the resource server to access protected resources. The resource server must validate and verify that the access token is valid and has not expired." }, { "code": null, "e": 2025, "s": 1972, "text": "There are two standard ways of sending credentials −" }, { "code": null, "e": 2173, "s": 2025, "text": "Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header." }, { "code": null, "e": 2321, "s": 2173, "text": "Bearer Token − The access token can only be placed in POST request body or GET URL parameter as a fallback option in the authorization HTTP header." }, { "code": null, "e": 2380, "s": 2321, "text": "They are included in the authorization header as follows −" }, { "code": null, "e": 2417, "s": 2380, "text": "Authorization: Bearer [token-value]\n" }, { "code": null, "e": 2431, "s": 2417, "text": "For Example −" }, { "code": null, "e": 2504, "s": 2431, "text": "GET/resource/1 HTTP /1.1\nHost: example.com\nAuthorization: Bearer abc...\n" }, { "code": null, "e": 2736, "s": 2504, "text": "MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner." }, { "code": null, "e": 2968, "s": 2736, "text": "MAC − A cryptographic Message Authentication Code (MAC) is computed using the elements of the request and is sent to the authorization header. Upon receiving the request, the MAC is then compared and computed by the resource owner." }, { "code": null, "e": 3040, "s": 2968, "text": "The following table shows the concepts of accessing protected resource." }, { "code": null, "e": 3136, "s": 3040, "text": "It is used to get the authorization code token for accessing the owner resources in the system." }, { "code": null, "e": 3279, "s": 3136, "text": "The resource server includes the \"WWW-Authenticate\" response header field, if the protected resource request contains an invalid access token." }, { "code": null, "e": 3286, "s": 3279, "text": " Print" }, { "code": null, "e": 3297, "s": 3286, "text": " Add Notes" } ]
Feature Selection using Logistic Regression Model | by Satyam Kumar | Towards Data Science
Feature Engineering is an important component of a data science model development pipeline. ‘More data leads to a better machine learning model’, holds true for the number of instances but not for the number of features. A data scientist spends most of the work time preparing relevant features to train a robust machine learning model. A raw dataset contains a lot of redundant features that may impact the performance of the model. Feature Selection is a feature engineering component that involves the removal of irrelevant features and picks the best set of features to train a robust machine learning model. Feature Selection methods reduce the dimensionality of the data and avoid the problem of the curse of dimensionality. I have broadly discussed 7 feature selection techniques in one of my previous articles: towardsdatascience.com In this article, we will discuss how to remove redundant features from the data using a logistic regression model with L1 regularization. Regularization is a technique used to tune the model by adding a penalty to the error function. Regularization can be used to train models that generalize better on the test or unseen data and prevents the algorithm from overfitting the training dataset. L2 regularization refers to the penalty which is equivalent to the square of the magnitude of coefficients, whereas L1 regularization introduces the penalty (shrinkage quantity) equivalent to the sum of the absolute value of coefficients. L1 regularization introduces sparsity in the dataset, and it can use to perform feature selection by eliminating the features that are not important. Lasso or L1 regularization shrinks the coefficients of redundant features to 0, therefore those features can be removed from the training sample. The credit card fraud detection dataset downloaded from Kaggle is used to demonstrate the feature selection implementation using Lasso Regression model Read the dataset and perform feature engineering (standardize) to make it fit to train a logistic regression model. Train a best-fit Logistic Regression model on the standardized training sample. Compute the coefficients of the Logistic Regression model using model.coef_ function, that returns with the weight vector of the logistic regression dividing plane. The dimensionality of the coefficient vector is the same as the number of features in the training dataset. The coefficient values equating to 0 are the redundant features and can be removed from the training sample. Observing from the above snapshot of the coefficient vector, we have 7 features that have coefficient values of 0. coef = model.coef_[0]imp_features = pd.Series(X_std.columns)[list(coef!=0)]X_train = X_train[imp_features]X_test = X_test[imp_features] Prior to feature selection implementation, the training sample had 29 features, which were reduced to 22 features after the removal of 7 redundant features. The parameter ‘C’ of the Logistic Regression model affects the coefficients term. When regularization gets progressively looser or the value of ‘C’ decreases, we get more coefficient values as 0. One must keep in mind to keep the right value of ‘C’ to get the desired number of redundant features. A higher value of ‘C’ may consider important features as redundant, whereas lower values of ‘C’ may not exclude the redundant features. Lasso Regression (Logistic Regression with L1-regularization) can be used to remove redundant features from the dataset. L1-regularization introduces sparsity in the dataset and shrinks the values of the coefficients of redundant features to 0. It is a very useful technique or hacks to reduce the dimensionality of the dataset by removing the irrelevant features. There are various other techniques for feature selection. I have discussed 7 such feature selection techniques in one of my previous articles: towardsdatascience.com [1] Scikit-learn documentation: https://scikit-learn.org/stable/auto_examples/linear_model/plot_logistic_path.html Thank You for Reading
[ { "code": null, "e": 392, "s": 171, "text": "Feature Engineering is an important component of a data science model development pipeline. ‘More data leads to a better machine learning model’, holds true for the number of instances but not for the number of features." }, { "code": null, "e": 784, "s": 392, "text": "A data scientist spends most of the work time preparing relevant features to train a robust machine learning model. A raw dataset contains a lot of redundant features that may impact the performance of the model. Feature Selection is a feature engineering component that involves the removal of irrelevant features and picks the best set of features to train a robust machine learning model." }, { "code": null, "e": 990, "s": 784, "text": "Feature Selection methods reduce the dimensionality of the data and avoid the problem of the curse of dimensionality. I have broadly discussed 7 feature selection techniques in one of my previous articles:" }, { "code": null, "e": 1013, "s": 990, "text": "towardsdatascience.com" }, { "code": null, "e": 1151, "s": 1013, "text": "In this article, we will discuss how to remove redundant features from the data using a logistic regression model with L1 regularization." }, { "code": null, "e": 1406, "s": 1151, "text": "Regularization is a technique used to tune the model by adding a penalty to the error function. Regularization can be used to train models that generalize better on the test or unseen data and prevents the algorithm from overfitting the training dataset." }, { "code": null, "e": 1645, "s": 1406, "text": "L2 regularization refers to the penalty which is equivalent to the square of the magnitude of coefficients, whereas L1 regularization introduces the penalty (shrinkage quantity) equivalent to the sum of the absolute value of coefficients." }, { "code": null, "e": 1941, "s": 1645, "text": "L1 regularization introduces sparsity in the dataset, and it can use to perform feature selection by eliminating the features that are not important. Lasso or L1 regularization shrinks the coefficients of redundant features to 0, therefore those features can be removed from the training sample." }, { "code": null, "e": 2093, "s": 1941, "text": "The credit card fraud detection dataset downloaded from Kaggle is used to demonstrate the feature selection implementation using Lasso Regression model" }, { "code": null, "e": 2209, "s": 2093, "text": "Read the dataset and perform feature engineering (standardize) to make it fit to train a logistic regression model." }, { "code": null, "e": 2289, "s": 2209, "text": "Train a best-fit Logistic Regression model on the standardized training sample." }, { "code": null, "e": 2454, "s": 2289, "text": "Compute the coefficients of the Logistic Regression model using model.coef_ function, that returns with the weight vector of the logistic regression dividing plane." }, { "code": null, "e": 2562, "s": 2454, "text": "The dimensionality of the coefficient vector is the same as the number of features in the training dataset." }, { "code": null, "e": 2786, "s": 2562, "text": "The coefficient values equating to 0 are the redundant features and can be removed from the training sample. Observing from the above snapshot of the coefficient vector, we have 7 features that have coefficient values of 0." }, { "code": null, "e": 2922, "s": 2786, "text": "coef = model.coef_[0]imp_features = pd.Series(X_std.columns)[list(coef!=0)]X_train = X_train[imp_features]X_test = X_test[imp_features]" }, { "code": null, "e": 3079, "s": 2922, "text": "Prior to feature selection implementation, the training sample had 29 features, which were reduced to 22 features after the removal of 7 redundant features." }, { "code": null, "e": 3377, "s": 3079, "text": "The parameter ‘C’ of the Logistic Regression model affects the coefficients term. When regularization gets progressively looser or the value of ‘C’ decreases, we get more coefficient values as 0. One must keep in mind to keep the right value of ‘C’ to get the desired number of redundant features." }, { "code": null, "e": 3513, "s": 3377, "text": "A higher value of ‘C’ may consider important features as redundant, whereas lower values of ‘C’ may not exclude the redundant features." }, { "code": null, "e": 3758, "s": 3513, "text": "Lasso Regression (Logistic Regression with L1-regularization) can be used to remove redundant features from the dataset. L1-regularization introduces sparsity in the dataset and shrinks the values of the coefficients of redundant features to 0." }, { "code": null, "e": 3878, "s": 3758, "text": "It is a very useful technique or hacks to reduce the dimensionality of the dataset by removing the irrelevant features." }, { "code": null, "e": 4021, "s": 3878, "text": "There are various other techniques for feature selection. I have discussed 7 such feature selection techniques in one of my previous articles:" }, { "code": null, "e": 4044, "s": 4021, "text": "towardsdatascience.com" }, { "code": null, "e": 4159, "s": 4044, "text": "[1] Scikit-learn documentation: https://scikit-learn.org/stable/auto_examples/linear_model/plot_logistic_path.html" } ]
Setting up TensorFlow (GPU) on Windows 10 | by Peter Jang | Towards Data Science
Personally, I despise spending hours setting up machine learning tools for training — especially on Windows. After many trials and errors for the past few years (i.e. Googling and StackOverflow-ing), I’ve decided to share a method I’ve come up with for setting up TensorFlow. I dedicate this article to other data scientists who are stuck on looking at command prompts filled with error messages. Warning: You must have a CUDA®-enabled GPU card. Install (in order): Visual Studio Anaconda NVIDIA CUDA Toolkit + cuDNN Before all else, install Visual Studio from here. Install the Community version because Professional and Enterprise require a subscription. Note: Visual Studio is not the same as VS Code IDE! Download and install Anaconda from here. You do not have to add Anaconda to PATH environment variable during installation. After installing Visual Studio, install NVIDIA CUDA Toolkit and cuDNN. To the current date (October 2020), you must install CUDA 10.1 and cuDNN SDK 7.6 (this is extremely important). Warning: The supported versions may change so make sure to check out the official TensorFlow docs. The latest CUDA version is 11 — please visit CUDA Archive and cuDNN Archive for earlier versions. Install CUDA by simply running the executable file (.exe). Unzip cuDNN library and move all the files to CUDA directory. If you haven’t changed the installation directory, your CUDA will be located here: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA Open Anaconda Prompt and check the version of Python. You can enter the command below to check the version of Python you are currently running. python --version Then, create a new Anaconda virtual environment: conda create -n tf python=PYTHON_VERSION tf can be changed to any other name (e.g. python_tensorflow) Remember to replace PYTHON_VERSION with your Python version (e.g. 3.8.5) Then, activate the environment you have just created: conda activate tf Finally, install TensorFlow: pip install tensorflow Do not pip install tensorflow-gpu as it will install an older version of TensorFlow (old tutorials on YouTube use this command). Test if TensorFlow has been installed correctly and if it can detect CUDA and cuDNN by running: python -c "import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([1000, 1000])))" If there are no errors, congratulations — you have successfully installed TensorFlow. I personally use Jupyter Notebook, Seaborn, and Matplotlib a lot, so I make sure to install these libraries by running: pip install jupyter ipykernel seaborn matplotlib Add the Anaconda environment you have created earlier to Jupyter Notebook. python -m ipykernel install --user --name ENVIRONMENT_NAME --display-name "KERNEL_DISPLAY_NAME" Return to the base conda environment and open up Jupyter Notebook: conda activate basejupyter notebook Create a new Jupyter Notebook and open it up: Run these three lines of code below: !python --versionimport tensorflow as tfprint("Num GPUs Available", len(tf.config.experimental.list_physical_devices('GPU'))) If it can detect your Python and your GPU, you have successfully installed TensorFlow (GPU) and essential tools for machine learning!
[ { "code": null, "e": 280, "s": 171, "text": "Personally, I despise spending hours setting up machine learning tools for training — especially on Windows." }, { "code": null, "e": 447, "s": 280, "text": "After many trials and errors for the past few years (i.e. Googling and StackOverflow-ing), I’ve decided to share a method I’ve come up with for setting up TensorFlow." }, { "code": null, "e": 568, "s": 447, "text": "I dedicate this article to other data scientists who are stuck on looking at command prompts filled with error messages." }, { "code": null, "e": 617, "s": 568, "text": "Warning: You must have a CUDA®-enabled GPU card." }, { "code": null, "e": 637, "s": 617, "text": "Install (in order):" }, { "code": null, "e": 651, "s": 637, "text": "Visual Studio" }, { "code": null, "e": 660, "s": 651, "text": "Anaconda" }, { "code": null, "e": 688, "s": 660, "text": "NVIDIA CUDA Toolkit + cuDNN" }, { "code": null, "e": 828, "s": 688, "text": "Before all else, install Visual Studio from here. Install the Community version because Professional and Enterprise require a subscription." }, { "code": null, "e": 880, "s": 828, "text": "Note: Visual Studio is not the same as VS Code IDE!" }, { "code": null, "e": 921, "s": 880, "text": "Download and install Anaconda from here." }, { "code": null, "e": 1003, "s": 921, "text": "You do not have to add Anaconda to PATH environment variable during installation." }, { "code": null, "e": 1074, "s": 1003, "text": "After installing Visual Studio, install NVIDIA CUDA Toolkit and cuDNN." }, { "code": null, "e": 1186, "s": 1074, "text": "To the current date (October 2020), you must install CUDA 10.1 and cuDNN SDK 7.6 (this is extremely important)." }, { "code": null, "e": 1285, "s": 1186, "text": "Warning: The supported versions may change so make sure to check out the official TensorFlow docs." }, { "code": null, "e": 1383, "s": 1285, "text": "The latest CUDA version is 11 — please visit CUDA Archive and cuDNN Archive for earlier versions." }, { "code": null, "e": 1442, "s": 1383, "text": "Install CUDA by simply running the executable file (.exe)." }, { "code": null, "e": 1587, "s": 1442, "text": "Unzip cuDNN library and move all the files to CUDA directory. If you haven’t changed the installation directory, your CUDA will be located here:" }, { "code": null, "e": 1638, "s": 1587, "text": "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA" }, { "code": null, "e": 1692, "s": 1638, "text": "Open Anaconda Prompt and check the version of Python." }, { "code": null, "e": 1782, "s": 1692, "text": "You can enter the command below to check the version of Python you are currently running." }, { "code": null, "e": 1799, "s": 1782, "text": "python --version" }, { "code": null, "e": 1848, "s": 1799, "text": "Then, create a new Anaconda virtual environment:" }, { "code": null, "e": 1889, "s": 1848, "text": "conda create -n tf python=PYTHON_VERSION" }, { "code": null, "e": 1950, "s": 1889, "text": "tf can be changed to any other name (e.g. python_tensorflow)" }, { "code": null, "e": 2023, "s": 1950, "text": "Remember to replace PYTHON_VERSION with your Python version (e.g. 3.8.5)" }, { "code": null, "e": 2077, "s": 2023, "text": "Then, activate the environment you have just created:" }, { "code": null, "e": 2095, "s": 2077, "text": "conda activate tf" }, { "code": null, "e": 2124, "s": 2095, "text": "Finally, install TensorFlow:" }, { "code": null, "e": 2147, "s": 2124, "text": "pip install tensorflow" }, { "code": null, "e": 2276, "s": 2147, "text": "Do not pip install tensorflow-gpu as it will install an older version of TensorFlow (old tutorials on YouTube use this command)." }, { "code": null, "e": 2372, "s": 2276, "text": "Test if TensorFlow has been installed correctly and if it can detect CUDA and cuDNN by running:" }, { "code": null, "e": 2462, "s": 2372, "text": "python -c \"import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([1000, 1000])))\"" }, { "code": null, "e": 2548, "s": 2462, "text": "If there are no errors, congratulations — you have successfully installed TensorFlow." }, { "code": null, "e": 2668, "s": 2548, "text": "I personally use Jupyter Notebook, Seaborn, and Matplotlib a lot, so I make sure to install these libraries by running:" }, { "code": null, "e": 2717, "s": 2668, "text": "pip install jupyter ipykernel seaborn matplotlib" }, { "code": null, "e": 2792, "s": 2717, "text": "Add the Anaconda environment you have created earlier to Jupyter Notebook." }, { "code": null, "e": 2888, "s": 2792, "text": "python -m ipykernel install --user --name ENVIRONMENT_NAME --display-name \"KERNEL_DISPLAY_NAME\"" }, { "code": null, "e": 2955, "s": 2888, "text": "Return to the base conda environment and open up Jupyter Notebook:" }, { "code": null, "e": 2991, "s": 2955, "text": "conda activate basejupyter notebook" }, { "code": null, "e": 3037, "s": 2991, "text": "Create a new Jupyter Notebook and open it up:" }, { "code": null, "e": 3074, "s": 3037, "text": "Run these three lines of code below:" }, { "code": null, "e": 3200, "s": 3074, "text": "!python --versionimport tensorflow as tfprint(\"Num GPUs Available\", len(tf.config.experimental.list_physical_devices('GPU')))" } ]
Java - String intern() Method
This method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. Here is the syntax of this method − public String intern() Here is the detail of parameters − This is a default method and this do not accept any parameters. This method returns a canonical representation for the string object. import java.io.*; public class Test { public static void main(String args[]) { String Str1 = new String("Welcome to Tutorialspoint.com"); String Str2 = new String("WELCOME TO SUTORIALSPOINT.COM"); System.out.print("Canonical representation:" ); System.out.println(Str1.intern()); System.out.print("Canonical representation:" ); System.out.println(Str2.intern()); } } This will produce the following result − Canonical representation: Welcome to Tutorialspoint.com Canonical representation: WELCOME TO SUTORIALSPOINT.COM 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": 2561, "s": 2377, "text": "This method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true." }, { "code": null, "e": 2598, "s": 2561, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2622, "s": 2598, "text": "public String intern()\n" }, { "code": null, "e": 2657, "s": 2622, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2721, "s": 2657, "text": "This is a default method and this do not accept any parameters." }, { "code": null, "e": 2791, "s": 2721, "text": "This method returns a canonical representation for the string object." }, { "code": null, "e": 3203, "s": 2791, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str1 = new String(\"Welcome to Tutorialspoint.com\");\n String Str2 = new String(\"WELCOME TO SUTORIALSPOINT.COM\");\n\n System.out.print(\"Canonical representation:\" );\n System.out.println(Str1.intern());\n\n System.out.print(\"Canonical representation:\" );\n System.out.println(Str2.intern());\n }\n}" }, { "code": null, "e": 3244, "s": 3203, "text": "This will produce the following result −" }, { "code": null, "e": 3357, "s": 3244, "text": "Canonical representation: Welcome to Tutorialspoint.com\nCanonical representation: WELCOME TO SUTORIALSPOINT.COM\n" }, { "code": null, "e": 3390, "s": 3357, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3406, "s": 3390, "text": " Malhar Lathkar" }, { "code": null, "e": 3439, "s": 3406, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3455, "s": 3439, "text": " Malhar Lathkar" }, { "code": null, "e": 3490, "s": 3455, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3504, "s": 3490, "text": " Anadi Sharma" }, { "code": null, "e": 3538, "s": 3504, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3552, "s": 3538, "text": " Tushar Kale" }, { "code": null, "e": 3589, "s": 3552, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3604, "s": 3589, "text": " Monica Mittal" }, { "code": null, "e": 3637, "s": 3604, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3656, "s": 3637, "text": " Arnab Chakraborty" }, { "code": null, "e": 3663, "s": 3656, "text": " Print" }, { "code": null, "e": 3674, "s": 3663, "text": " Add Notes" } ]
Find number of subarrays with even sum - GeeksforGeeks
10 Feb, 2022 Given an array, find the number of subarrays whose sum is even. Example : Input : arr[] = {1, 2, 2, 3, 4, 1} Output : 9 There are possible subarrays with even sum. The subarrays are 1) {1, 2, 2, 3} Sum = 8 2) {1, 2, 2, 3, 4} Sum = 12 3) {2} Sum = 2 (At index 1) 4) {2, 2} Sum = 4 5) {2, 2, 3, 4, 1} Sum = 12 6) {2} Sum = 2 (At index 2) 7) {2, 3, 4, 1} Sum = 10 8) {3, 4, 1} Sum = 8 9) {4} Sum = 4 O(n2) time and O(1) space method [Brute Force] We can simply generate all the possible sub-arrays and find whether the sum of all the elements in them is an even or not. If it is even then we will count that sub-array otherwise neglect it. C++ Java Python3 C# PHP Javascript /* C++ program to count number of sub-arrays whose sum is even using brute force Time Complexity - O(N^2) Space Complexity - O(1) */#include<iostream>using namespace std; int countEvenSum(int arr[], int n){ int result = 0; // Find sum of all subarrays and increment // result if sum is even for (int i=0; i<=n-1; i++) { int sum = 0; for (int j=i; j<=n-1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 1}; int n = sizeof (arr) / sizeof (arr[0]); cout << "The Number of Subarrays with even" " sum is " << countEvenSum (arr, n); return (0);} // Java program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)import java.io.*; class GFG{static int countEvenSum(int arr[], int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is even for (int i = 0; i <= n - 1; i++) { int sum = 0; for (int j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codepublic static void main (String[] args){int arr[] = {1, 2, 2, 3, 4, 1};int n = arr.length; System.out.print("The Number of Subarrays"+ " with even sum is "); System.out.println(countEvenSum(arr, n));}} // This code is contributed by ajit # Python 3 program to count number# of sub-arrays whose sum is even# using brute force# Time Complexity - O(N^2)# Space Complexity - O(1) def countEvenSum(arr, n): result = 0 # Find sum of all subarrays and # increment result if sum is even for i in range(0, n, 1): sum = 0 for j in range(i, n, 1): sum = sum + arr[j] if (sum % 2 == 0): result = result + 1 return (result) # Driver codeif __name__ == '__main__': arr = [1, 2, 2, 3, 4, 1] n = len(arr) print("The Number of Subarrays" , "with even sum is", countEvenSum (arr, n)) # This code is contributed by# Surendra_Gangwar // C# program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)using System; class GFG{static int countEvenSum(int []arr, int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is even for (int i = 0; i <= n - 1; i++) { int sum = 0; for (int j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codestatic public void Main (){ int []arr = {1, 2, 2, 3, 4, 1}; int n = arr.Length; Console.Write("The Number of Subarrays"+ " with even sum is "); Console.WriteLine(countEvenSum(arr, n)); }} // This code is contributed by m_kit <?php// PHP program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)function countEvenSum($arr, $n){ $result = 0; // Find sum of all subarrays // and increment result if // sum is even for ($i = 0; $i <= $n - 1; $i++) { $sum = 0; for ($j = $i; $j <= $n - 1; $j++) { $sum = $sum + $arr[$j]; if ($sum % 2 == 0) $result++; } } return ($result);} // Driver code$arr = array(1, 2, 2, 3, 4, 1);$n = sizeof ($arr); echo "The Number of Subarrays ", "with even sum is " , countEvenSum ($arr, $n); // This code is contributed by ajit?> <script> // Javascript program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1) function countEvenSum(arr, n){ let result = 0; // Find sum of all subarrays // and increment result if // sum is even for (let i = 0; i <= n - 1; i++) { let sum = 0; for (let j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver Code let arr = [1, 2, 2, 3, 4, 1];let n = arr.length; document.write("The Number of Subarrays"+ " with even sum is "); document.write(countEvenSum(arr, n)); </script> The Number of Subarrays with even sum is 9 O(n) Time and O(1) Space Method [Efficient] If we do compute the cumulative sum array in temp[] of our input array, then we can see that the sub-array starting from i and ending at j, has an even sum if temp[] if (temp[j] – temp[i]) % 2 = 0. So, instead of building a cumulative sum array we build a cumulative sum modulo 2 array, and find how many times 0 and 1 appears in temp[] array using handshake formula. [n * (n-1) /2] C++ Java Python 3 C# PHP Javascript /* C++ program to count number of sub-arrayswith even sum using an efficient algorithmTime Complexity - O(N)Space Complexity - O(1)*/#include<iostream>using namespace std; int countEvenSum(int arr[], int n){ // A temporary array of size 2. temp[0] is // going to store count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as 1 because there // a single even element is also counted as // a subarray int temp[2] = {1, 0}; // Initialize count. sum is sum of elements // under modulo 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum of arr[0..i] // under modulo 2 and increments even/odd count // according to sum's value for (int i=0; i<=n-1; i++) { // 2 is added to handle negative numbers sum = ( (sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to count even subarrays // (Note that an even can be formed by two even // or two odd) result = result + (temp[0]*(temp[0]-1)/2); result = result + (temp[1]*(temp[1]-1)/2); return (result);} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 1}; int n = sizeof (arr) / sizeof (arr[0]); cout << "The Number of Subarrays with even" " sum is " << countEvenSum (arr, n); return (0);} // Java program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)import java.io.*; class GFG{static int countEvenSum(int arr[], int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray int temp[] = {1, 0}; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result);} // Driver codepublic static void main (String[] args){ int arr[] = {1, 2, 2, 3, 4, 1};int n = arr.length; System.out.println("The Number of Subarrays"+ " with even sum is " + countEvenSum (arr, n));}} // This code is contributed by ajit # Python 3 program to count number of sub-arrays# with even sum using an efficient algorithm# Time Complexity - O(N)# Space Complexity - O(1)def countEvenSum(arr, n): # A temporary array of size 2. temp[0] is # going to store count of even subarrays # and temp[1] count of odd. # temp[0] is initialized as 1 because there # a single even element is also counted as # a subarray temp = [1, 0] # Initialize count. sum is sum of elements # under modulo 2 and ending with arr[i]. result = 0 sum = 0 # i'th iteration computes sum of arr[0..i] # under modulo 2 and increments even/odd # count according to sum's value for i in range( n): # 2 is added to handle negative numbers sum = ( (sum + arr[i]) % 2 + 2) % 2 # Increment even/odd count temp[sum]+= 1 # Use handshake lemma to count even subarrays # (Note that an even can be formed by two even # or two odd) result = result + (temp[0] * (temp[0] - 1) // 2) result = result + (temp[1] * (temp[1] - 1) // 2) return (result) # Driver codeif __name__ == "__main__": arr = [1, 2, 2, 3, 4, 1] n = len(arr) print( "The Number of Subarrays with even" " sum is" , countEvenSum (arr, n)) # This code is contributed by ita_c // C# program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)using System; class GFG{static int countEvenSum(int []arr, int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray int []temp = {1, 0}; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even // or odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result);} // Driver codestatic public void Main (){ int []arr = {1, 2, 2, 3, 4, 1}; int n = arr.Length; Console.WriteLine("The Number of Subarrays"+ " with even sum is " + countEvenSum (arr, n));}} // This code is contributed// by akt_mit <?php// PHP program to count number// of sub-arrays with even sum// using an efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)*/function countEvenSum($arr, $n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays and // temp[1] count of odd. temp[0] // is initialized as 1 because // there a single even element // is also counted as a subarray $temp = array(1, 0); // Initialize count. sum is // sum of elements under // modulo 2 and ending with arr[i]. $result = 0; $sum = 0; // i'th iteration computes // sum of arr[0..i] under // modulo 2 and increments // even/odd count according // to sum's value for ($i = 0; $i <= $n - 1; $i++) { // 2 is added to handle // negative numbers $sum = (($sum + $arr[$i]) % 2 + 2) % 2; // Increment even/odd // count $temp[$sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) $result = $result + (int)($temp[0] * ($temp[0] - 1) / 2); $result = $result + (int)($temp[1] * ($temp[1] - 1) / 2); return ($result);} // Driver code$arr = array (1, 2, 2, 3, 4, 1);$n = sizeof ($arr); echo "The Number of Subarrays " . "with even", " sum is " , countEvenSum ($arr, $n); // This code is contributed by ajit?> <script>// Javascript program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1) function countEvenSum(arr,n) { // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray let temp = [1, 0]; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. let result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (let i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result); } // Driver code let arr=[1, 2, 2, 3, 4, 1]; let n = arr.length; document.write("The Number of Subarrays"+ " with even sum is " + countEvenSum (arr, n)); // This code is contributed by rag2127</script> Output : The Number of Subarrays with even sum is 9 O(n) Time and O(1) Space Method (bottom-up-approach) If we start counting from last index and keep track of number of subarrays with even sum so far starting from present index then we can calculate number of subarrays with even sum starting from previous index C++ Java Python3 C# Javascript /* C++ program to count number of sub-arrayswith even sum using an efficient algorithmTime Complexity - O(N)Space Complexity - O(1)*/#include <iostream>using namespace std; long long countEvenSum(int a[], int n){ // Result may be large enough not to // fit in int; long long res = 0; // To keep track of subarrays with even sum // starting from index i; int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { /* s is the count of subarrays starting from * index i+1 whose sum was even*/ /* If a[i] is odd then all subarrays starting from index i+1 which was odd becomes even when a[i] gets added to it. */ s = n - i - 1 - s; } else { /* If a[i] is even then all subarrays starting from index i+1 which was even remains even and one extra a[i] even subarray gets added to it. */ s = s + 1; } res = res + s; } return res;} // Driver Codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The Number of Subarrays with even" " sum is " << countEvenSum(arr, n); return 0;} // This code is contributed by Aditya Anand // Java program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)import java.io.*; class GFG { public static long countEvenSum(int a[], int n) { // result may be large enough not to // fit in int; long res = 0; // to keep track of subarrays with even // sum starting from index i int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 2, 3, 4, 1 }; int n = arr.length; System.out.println("The Number of Subarrays" + " with even sum is " + countEvenSum(arr, n)); }} // This code is contributed by Aditya Anand # Python 3 program to count number of sub-arrays# with even sum using an efficient algorithm# Time Complexity - O(N)# Space Complexity - O(1) def countEvenSum(arr, n): # result may be large # enough not to fit in int; res = 0 # to keep track of subarrays # with even sum starting from index i s = 0 for i in reversed(range(n)): if arr[i] % 2 == 1: # s is the count of subarrays # starting from index i+1 # whose sum was even """ if a[i] is odd then all subarrays starting from index i+1 which was odd becomes even when a[i] gets added to it. """ s = n-i-1-s else: """ if a[i] is even then all subarrays starting from index i+1 which was even remains even and one extra a[i] even subarray gets added to it. """ s = s+1 res = res + s return res # Driver codeif __name__ == "__main__": arr = [1, 2, 2, 3, 4, 1] n = len(arr) print("The Number of Subarrays with even" " sum is", countEvenSum(arr, n)) # This code is contributed by Aditya Anand // C# program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)using System;public class GFG{ public static long countEvenSum(int[] a, int n) { // result may be large enough not to // fit in int; long res = 0; // to keep track of subarrays with even // sum starting from index i int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } // Driver Code static public void Main () { int[] arr = { 1, 2, 2, 3, 4, 1 }; int n = arr.Length; Console.WriteLine("The Number of Subarrays" + " with even sum is " + countEvenSum(arr, n)); }} // This code is contributed by avanitrachhadiya2155 <script> // Javascript program to count // number of sub-arrays // with even sum using an // efficient algorithm // Time Complexity - O(N) // Space Complexity - O(1) function countEvenSum(a, n) { // result may be large enough not to // fit in int; let res = 0; // to keep track of subarrays with even // sum starting from index i let s = 0; for (let i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } let arr = [ 1, 2, 2, 3, 4, 1 ]; let n = arr.length; document.write("The Number of Subarrays" + " with even sum is " + countEvenSum(arr, n)); </script> The Number of Subarrays with even sum is 9 This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [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 repejufac SURENDRA_GANGWAR ukasp adityaanand12017 avanitrachhadiya2155 souravghosh0416 rag2127 divyesh072019 sagar0719kumar Directi subarray subarray-sum Arrays Mathematical Directi Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Queue | Set 1 (Introduction and Array Implementation) Linear Search Python | Using 2D arrays/lists the right way Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 24325, "s": 24297, "text": "\n10 Feb, 2022" }, { "code": null, "e": 24389, "s": 24325, "text": "Given an array, find the number of subarrays whose sum is even." }, { "code": null, "e": 24400, "s": 24389, "text": "Example : " }, { "code": null, "e": 24735, "s": 24400, "text": "Input : arr[] = {1, 2, 2, 3, 4, 1} \nOutput : 9\n\nThere are possible subarrays with even\nsum. The subarrays are \n1) {1, 2, 2, 3} Sum = 8\n2) {1, 2, 2, 3, 4} Sum = 12\n3) {2} Sum = 2 (At index 1)\n4) {2, 2} Sum = 4\n5) {2, 2, 3, 4, 1} Sum = 12\n6) {2} Sum = 2 (At index 2)\n7) {2, 3, 4, 1} Sum = 10\n8) {3, 4, 1} Sum = 8\n9) {4} Sum = 4 " }, { "code": null, "e": 24976, "s": 24735, "text": "O(n2) time and O(1) space method [Brute Force] We can simply generate all the possible sub-arrays and find whether the sum of all the elements in them is an even or not. If it is even then we will count that sub-array otherwise neglect it. " }, { "code": null, "e": 24980, "s": 24976, "text": "C++" }, { "code": null, "e": 24985, "s": 24980, "text": "Java" }, { "code": null, "e": 24993, "s": 24985, "text": "Python3" }, { "code": null, "e": 24996, "s": 24993, "text": "C#" }, { "code": null, "e": 25000, "s": 24996, "text": "PHP" }, { "code": null, "e": 25011, "s": 25000, "text": "Javascript" }, { "code": "/* C++ program to count number of sub-arrays whose sum is even using brute force Time Complexity - O(N^2) Space Complexity - O(1) */#include<iostream>using namespace std; int countEvenSum(int arr[], int n){ int result = 0; // Find sum of all subarrays and increment // result if sum is even for (int i=0; i<=n-1; i++) { int sum = 0; for (int j=i; j<=n-1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 1}; int n = sizeof (arr) / sizeof (arr[0]); cout << \"The Number of Subarrays with even\" \" sum is \" << countEvenSum (arr, n); return (0);}", "e": 25753, "s": 25011, "text": null }, { "code": "// Java program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)import java.io.*; class GFG{static int countEvenSum(int arr[], int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is even for (int i = 0; i <= n - 1; i++) { int sum = 0; for (int j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codepublic static void main (String[] args){int arr[] = {1, 2, 2, 3, 4, 1};int n = arr.length; System.out.print(\"The Number of Subarrays\"+ \" with even sum is \"); System.out.println(countEvenSum(arr, n));}} // This code is contributed by ajit", "e": 26625, "s": 25753, "text": null }, { "code": "# Python 3 program to count number# of sub-arrays whose sum is even# using brute force# Time Complexity - O(N^2)# Space Complexity - O(1) def countEvenSum(arr, n): result = 0 # Find sum of all subarrays and # increment result if sum is even for i in range(0, n, 1): sum = 0 for j in range(i, n, 1): sum = sum + arr[j] if (sum % 2 == 0): result = result + 1 return (result) # Driver codeif __name__ == '__main__': arr = [1, 2, 2, 3, 4, 1] n = len(arr) print(\"The Number of Subarrays\" , \"with even sum is\", countEvenSum (arr, n)) # This code is contributed by# Surendra_Gangwar", "e": 27313, "s": 26625, "text": null }, { "code": "// C# program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)using System; class GFG{static int countEvenSum(int []arr, int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is even for (int i = 0; i <= n - 1; i++) { int sum = 0; for (int j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver codestatic public void Main (){ int []arr = {1, 2, 2, 3, 4, 1}; int n = arr.Length; Console.Write(\"The Number of Subarrays\"+ \" with even sum is \"); Console.WriteLine(countEvenSum(arr, n)); }} // This code is contributed by m_kit", "e": 28187, "s": 27313, "text": null }, { "code": "<?php// PHP program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1)function countEvenSum($arr, $n){ $result = 0; // Find sum of all subarrays // and increment result if // sum is even for ($i = 0; $i <= $n - 1; $i++) { $sum = 0; for ($j = $i; $j <= $n - 1; $j++) { $sum = $sum + $arr[$j]; if ($sum % 2 == 0) $result++; } } return ($result);} // Driver code$arr = array(1, 2, 2, 3, 4, 1);$n = sizeof ($arr); echo \"The Number of Subarrays \", \"with even sum is \" , countEvenSum ($arr, $n); // This code is contributed by ajit?>", "e": 28899, "s": 28187, "text": null }, { "code": "<script> // Javascript program to count number// of sub-arrays whose sum is// even using brute force// Time Complexity - O(N^2)// Space Complexity - O(1) function countEvenSum(arr, n){ let result = 0; // Find sum of all subarrays // and increment result if // sum is even for (let i = 0; i <= n - 1; i++) { let sum = 0; for (let j = i; j <= n - 1; j++) { sum = sum + arr[j]; if (sum % 2 == 0) result++; } } return (result);} // Driver Code let arr = [1, 2, 2, 3, 4, 1];let n = arr.length; document.write(\"The Number of Subarrays\"+ \" with even sum is \"); document.write(countEvenSum(arr, n)); </script>", "e": 29676, "s": 28899, "text": null }, { "code": null, "e": 29719, "s": 29676, "text": "The Number of Subarrays with even sum is 9" }, { "code": null, "e": 30148, "s": 29719, "text": " O(n) Time and O(1) Space Method [Efficient] If we do compute the cumulative sum array in temp[] of our input array, then we can see that the sub-array starting from i and ending at j, has an even sum if temp[] if (temp[j] – temp[i]) % 2 = 0. So, instead of building a cumulative sum array we build a cumulative sum modulo 2 array, and find how many times 0 and 1 appears in temp[] array using handshake formula. [n * (n-1) /2]" }, { "code": null, "e": 30152, "s": 30148, "text": "C++" }, { "code": null, "e": 30157, "s": 30152, "text": "Java" }, { "code": null, "e": 30166, "s": 30157, "text": "Python 3" }, { "code": null, "e": 30169, "s": 30166, "text": "C#" }, { "code": null, "e": 30173, "s": 30169, "text": "PHP" }, { "code": null, "e": 30184, "s": 30173, "text": "Javascript" }, { "code": "/* C++ program to count number of sub-arrayswith even sum using an efficient algorithmTime Complexity - O(N)Space Complexity - O(1)*/#include<iostream>using namespace std; int countEvenSum(int arr[], int n){ // A temporary array of size 2. temp[0] is // going to store count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as 1 because there // a single even element is also counted as // a subarray int temp[2] = {1, 0}; // Initialize count. sum is sum of elements // under modulo 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum of arr[0..i] // under modulo 2 and increments even/odd count // according to sum's value for (int i=0; i<=n-1; i++) { // 2 is added to handle negative numbers sum = ( (sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to count even subarrays // (Note that an even can be formed by two even // or two odd) result = result + (temp[0]*(temp[0]-1)/2); result = result + (temp[1]*(temp[1]-1)/2); return (result);} // Driver codeint main(){ int arr[] = {1, 2, 2, 3, 4, 1}; int n = sizeof (arr) / sizeof (arr[0]); cout << \"The Number of Subarrays with even\" \" sum is \" << countEvenSum (arr, n); return (0);}", "e": 31543, "s": 30184, "text": null }, { "code": "// Java program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)import java.io.*; class GFG{static int countEvenSum(int arr[], int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray int temp[] = {1, 0}; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result);} // Driver codepublic static void main (String[] args){ int arr[] = {1, 2, 2, 3, 4, 1};int n = arr.length; System.out.println(\"The Number of Subarrays\"+ \" with even sum is \" + countEvenSum (arr, n));}} // This code is contributed by ajit", "e": 33119, "s": 31543, "text": null }, { "code": "# Python 3 program to count number of sub-arrays# with even sum using an efficient algorithm# Time Complexity - O(N)# Space Complexity - O(1)def countEvenSum(arr, n): # A temporary array of size 2. temp[0] is # going to store count of even subarrays # and temp[1] count of odd. # temp[0] is initialized as 1 because there # a single even element is also counted as # a subarray temp = [1, 0] # Initialize count. sum is sum of elements # under modulo 2 and ending with arr[i]. result = 0 sum = 0 # i'th iteration computes sum of arr[0..i] # under modulo 2 and increments even/odd # count according to sum's value for i in range( n): # 2 is added to handle negative numbers sum = ( (sum + arr[i]) % 2 + 2) % 2 # Increment even/odd count temp[sum]+= 1 # Use handshake lemma to count even subarrays # (Note that an even can be formed by two even # or two odd) result = result + (temp[0] * (temp[0] - 1) // 2) result = result + (temp[1] * (temp[1] - 1) // 2) return (result) # Driver codeif __name__ == \"__main__\": arr = [1, 2, 2, 3, 4, 1] n = len(arr) print( \"The Number of Subarrays with even\" \" sum is\" , countEvenSum (arr, n)) # This code is contributed by ita_c", "e": 34412, "s": 33119, "text": null }, { "code": "// C# program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)using System; class GFG{static int countEvenSum(int []arr, int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray int []temp = {1, 0}; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even // or odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result);} // Driver codestatic public void Main (){ int []arr = {1, 2, 2, 3, 4, 1}; int n = arr.Length; Console.WriteLine(\"The Number of Subarrays\"+ \" with even sum is \" + countEvenSum (arr, n));}} // This code is contributed// by akt_mit", "e": 36002, "s": 34412, "text": null }, { "code": "<?php// PHP program to count number// of sub-arrays with even sum// using an efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)*/function countEvenSum($arr, $n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays and // temp[1] count of odd. temp[0] // is initialized as 1 because // there a single even element // is also counted as a subarray $temp = array(1, 0); // Initialize count. sum is // sum of elements under // modulo 2 and ending with arr[i]. $result = 0; $sum = 0; // i'th iteration computes // sum of arr[0..i] under // modulo 2 and increments // even/odd count according // to sum's value for ($i = 0; $i <= $n - 1; $i++) { // 2 is added to handle // negative numbers $sum = (($sum + $arr[$i]) % 2 + 2) % 2; // Increment even/odd // count $temp[$sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) $result = $result + (int)($temp[0] * ($temp[0] - 1) / 2); $result = $result + (int)($temp[1] * ($temp[1] - 1) / 2); return ($result);} // Driver code$arr = array (1, 2, 2, 3, 4, 1);$n = sizeof ($arr); echo \"The Number of Subarrays \" . \"with even\", \" sum is \" , countEvenSum ($arr, $n); // This code is contributed by ajit?>", "e": 37508, "s": 36002, "text": null }, { "code": "<script>// Javascript program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1) function countEvenSum(arr,n) { // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single even // element is also counted as // a subarray let temp = [1, 0]; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. let result = 0, sum = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (let i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers sum = ((sum + arr[i]) % 2 + 2) % 2; // Increment even/odd count temp[sum]++; } // Use handshake lemma to // count even subarrays // (Note that an even can // be formed by two even // or two odd) result = result + (temp[0] * (temp[0] - 1) / 2); result = result + (temp[1] * (temp[1] - 1) / 2); return (result); } // Driver code let arr=[1, 2, 2, 3, 4, 1]; let n = arr.length; document.write(\"The Number of Subarrays\"+ \" with even sum is \" + countEvenSum (arr, n)); // This code is contributed by rag2127</script>", "e": 39214, "s": 37508, "text": null }, { "code": null, "e": 39224, "s": 39214, "text": "Output : " }, { "code": null, "e": 39267, "s": 39224, "text": "The Number of Subarrays with even sum is 9" }, { "code": null, "e": 39320, "s": 39267, "text": "O(n) Time and O(1) Space Method (bottom-up-approach)" }, { "code": null, "e": 39529, "s": 39320, "text": "If we start counting from last index and keep track of number of subarrays with even sum so far starting from present index then we can calculate number of subarrays with even sum starting from previous index" }, { "code": null, "e": 39533, "s": 39529, "text": "C++" }, { "code": null, "e": 39538, "s": 39533, "text": "Java" }, { "code": null, "e": 39546, "s": 39538, "text": "Python3" }, { "code": null, "e": 39549, "s": 39546, "text": "C#" }, { "code": null, "e": 39560, "s": 39549, "text": "Javascript" }, { "code": "/* C++ program to count number of sub-arrayswith even sum using an efficient algorithmTime Complexity - O(N)Space Complexity - O(1)*/#include <iostream>using namespace std; long long countEvenSum(int a[], int n){ // Result may be large enough not to // fit in int; long long res = 0; // To keep track of subarrays with even sum // starting from index i; int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { /* s is the count of subarrays starting from * index i+1 whose sum was even*/ /* If a[i] is odd then all subarrays starting from index i+1 which was odd becomes even when a[i] gets added to it. */ s = n - i - 1 - s; } else { /* If a[i] is even then all subarrays starting from index i+1 which was even remains even and one extra a[i] even subarray gets added to it. */ s = s + 1; } res = res + s; } return res;} // Driver Codeint main(){ int arr[] = { 1, 2, 2, 3, 4, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The Number of Subarrays with even\" \" sum is \" << countEvenSum(arr, n); return 0;} // This code is contributed by Aditya Anand", "e": 40896, "s": 39560, "text": null }, { "code": "// Java program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)import java.io.*; class GFG { public static long countEvenSum(int a[], int n) { // result may be large enough not to // fit in int; long res = 0; // to keep track of subarrays with even // sum starting from index i int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 2, 3, 4, 1 }; int n = arr.length; System.out.println(\"The Number of Subarrays\" + \" with even sum is \" + countEvenSum(arr, n)); }} // This code is contributed by Aditya Anand", "e": 42370, "s": 40896, "text": null }, { "code": "# Python 3 program to count number of sub-arrays# with even sum using an efficient algorithm# Time Complexity - O(N)# Space Complexity - O(1) def countEvenSum(arr, n): # result may be large # enough not to fit in int; res = 0 # to keep track of subarrays # with even sum starting from index i s = 0 for i in reversed(range(n)): if arr[i] % 2 == 1: # s is the count of subarrays # starting from index i+1 # whose sum was even \"\"\" if a[i] is odd then all subarrays starting from index i+1 which was odd becomes even when a[i] gets added to it. \"\"\" s = n-i-1-s else: \"\"\" if a[i] is even then all subarrays starting from index i+1 which was even remains even and one extra a[i] even subarray gets added to it. \"\"\" s = s+1 res = res + s return res # Driver codeif __name__ == \"__main__\": arr = [1, 2, 2, 3, 4, 1] n = len(arr) print(\"The Number of Subarrays with even\" \" sum is\", countEvenSum(arr, n)) # This code is contributed by Aditya Anand", "e": 43582, "s": 42370, "text": null }, { "code": "// C# program to count// number of sub-arrays// with even sum using an// efficient algorithm// Time Complexity - O(N)// Space Complexity - O(1)using System;public class GFG{ public static long countEvenSum(int[] a, int n) { // result may be large enough not to // fit in int; long res = 0; // to keep track of subarrays with even // sum starting from index i int s = 0; for (int i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } // Driver Code static public void Main () { int[] arr = { 1, 2, 2, 3, 4, 1 }; int n = arr.Length; Console.WriteLine(\"The Number of Subarrays\" + \" with even sum is \" + countEvenSum(arr, n)); }} // This code is contributed by avanitrachhadiya2155", "e": 44874, "s": 43582, "text": null }, { "code": "<script> // Javascript program to count // number of sub-arrays // with even sum using an // efficient algorithm // Time Complexity - O(N) // Space Complexity - O(1) function countEvenSum(a, n) { // result may be large enough not to // fit in int; let res = 0; // to keep track of subarrays with even // sum starting from index i let s = 0; for (let i = n - 1; i >= 0; i--) { if (a[i] % 2 == 1) { // s is the count of subarrays starting from // index i+1 whose sum was even /*if a[i] is odd then all subarrays starting from index i+1 which was odd becomeseven when a[i] gets added to it.*/ s = n - i - 1 - s; } else { /*if a[i] is even then all subarrays starting from index i+1 which was even remainseven and one extra a[i] even subarray gets added to it.*/ s = s + 1; } res = res + s; } return res; } let arr = [ 1, 2, 2, 3, 4, 1 ]; let n = arr.length; document.write(\"The Number of Subarrays\" + \" with even sum is \" + countEvenSum(arr, n)); </script>", "e": 46083, "s": 44874, "text": null }, { "code": null, "e": 46126, "s": 46083, "text": "The Number of Subarrays with even sum is 9" }, { "code": null, "e": 46521, "s": 46126, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [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": 46527, "s": 46521, "text": "jit_t" }, { "code": null, "e": 46537, "s": 46527, "text": "repejufac" }, { "code": null, "e": 46554, "s": 46537, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 46560, "s": 46554, "text": "ukasp" }, { "code": null, "e": 46577, "s": 46560, "text": "adityaanand12017" }, { "code": null, "e": 46598, "s": 46577, "text": "avanitrachhadiya2155" }, { "code": null, "e": 46614, "s": 46598, "text": "souravghosh0416" }, { "code": null, "e": 46622, "s": 46614, "text": "rag2127" }, { "code": null, "e": 46636, "s": 46622, "text": "divyesh072019" }, { "code": null, "e": 46651, "s": 46636, "text": "sagar0719kumar" }, { "code": null, "e": 46659, "s": 46651, "text": "Directi" }, { "code": null, "e": 46668, "s": 46659, "text": "subarray" }, { "code": null, "e": 46681, "s": 46668, "text": "subarray-sum" }, { "code": null, "e": 46688, "s": 46681, "text": "Arrays" }, { "code": null, "e": 46701, "s": 46688, "text": "Mathematical" }, { "code": null, "e": 46709, "s": 46701, "text": "Directi" }, { "code": null, "e": 46716, "s": 46709, "text": "Arrays" }, { "code": null, "e": 46729, "s": 46716, "text": "Mathematical" }, { "code": null, "e": 46827, "s": 46729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46836, "s": 46827, "text": "Comments" }, { "code": null, "e": 46849, "s": 46836, "text": "Old Comments" }, { "code": null, "e": 46897, "s": 46849, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 46929, "s": 46897, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 46983, "s": 46929, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 46997, "s": 46983, "text": "Linear Search" }, { "code": null, "e": 47042, "s": 46997, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 47102, "s": 47042, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 47117, "s": 47102, "text": "C++ Data Types" }, { "code": null, "e": 47160, "s": 47117, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 47179, "s": 47160, "text": "Coin Change | DP-7" } ]
Android - Image Switcher
Sometimes you don't want an image to appear abruptly on the screen, rather you want to apply some kind of animation to the image when it transitions from one image to another. This is supported by android in the form of ImageSwitcher. An image switcher allows you to add some transitions on the images through the way they appear on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is given below − <ImageSwitcher android:id="@+id/imageSwitcher1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > </ImageSwitcher> Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its syntax is given below − private ImageSwitcher imageSwitcher; imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1); The next thing we need to do implement the ViewFactory interface and implement unimplemented method that returns an imageView. Its syntax is below − imageSwitcher.setImageResource(R.drawable.ic_launcher); imageSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView myView = new ImageView(getApplicationContext()); return myView; } } The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below − Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); imageSwitcher.setInAnimation(in); imageSwitcher.setOutAnimation(out); The method setInAnimaton sets the animation of the appearance of the object on the screen whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation object. Apart from these methods, there are other methods defined in the ImageSwitcher class. They are defined below − setImageDrawable(Drawable drawable) Sets an image with image switcher. The image is passed in the form of bitmap setImageResource(int resid) Sets an image with image switcher. The image is passed in the form of integer id setImageURI(Uri uri) Sets an image with image switcher. THe image is passed in the form of URI ImageSwitcher(Context context, AttributeSet attrs) Returns an image switcher object with already setting some attributes passed in the method onInitializeAccessibilityEvent (AccessibilityEvent event) Initializes an AccessibilityEvent with information about this View which is the event source onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info) Initializes an AccessibilityNodeInfo with information about this view The below example demonstrates some of the image switcher effects on the bitmap. It crates a basic application that allows you to view the animation effects on the images. To experiment with this example , you need to run this on an actual device. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.app.ActionBar.LayoutParams; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; public class MainActivity extends Activity { private ImageSwitcher sw; private Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); sw = (ImageSwitcher) findViewById(R.id.imageSwitcher); sw.setFactory(new ViewFactory() { @Override public View makeView() { ImageView myView = new ImageView(getApplicationContext()); myView.setScaleType(ImageView.ScaleType.FIT_CENTER); myView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return myView; } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "previous Image", Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.abc); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Next Image", Toast.LENGTH_LONG).show(); sw.setImageResource(R.drawable.tp); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="Gestures Example" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <ImageSwitcher android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageSwitcher" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:layout_marginTop="168dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/left" android:id="@+id/button" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/right" android:id="@+id/button2" android:layout_alignParentBottom="true" android:layout_alignLeft="@+id/button" android:layout_alignStart="@+id/button" /> </RelativeLayout> Following is the content of Strings.xml file. <resources> <string name="app_name">My Application</string> <string name="left"><![CDATA[<]]></string> <string name="right"><![CDATA[>]]></string> </resources> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.sairamkrishna.myapplication.MainActivity" android:label="@string/app_name" > <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 we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Now if you will look at your device screen , you will see the two buttons. Now just select the upper button that right arrow. An image would appear from right and move towards left. It is shown below − Now tap on the below button, that will bring back the previous image with some transition. It is shown below − 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3842, "s": 3607, "text": "Sometimes you don't want an image to appear abruptly on the screen, rather you want to apply some kind of animation to the image when it transitions from one image to another. This is supported by android in the form of ImageSwitcher." }, { "code": null, "e": 4052, "s": 3842, "text": "An image switcher allows you to add some transitions on the images through the way they appear on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is given below −" }, { "code": null, "e": 4283, "s": 4052, "text": "<ImageSwitcher\n android:id=\"@+id/imageSwitcher1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\" >\n</ImageSwitcher>" }, { "code": null, "e": 4409, "s": 4283, "text": "Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its syntax is given below −" }, { "code": null, "e": 4513, "s": 4409, "text": "private ImageSwitcher imageSwitcher;\nimageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);\n" }, { "code": null, "e": 4662, "s": 4513, "text": "The next thing we need to do implement the ViewFactory interface and implement unimplemented method that returns an imageView. Its syntax is below −" }, { "code": null, "e": 4884, "s": 4662, "text": "imageSwitcher.setImageResource(R.drawable.ic_launcher);\nimageSwitcher.setFactory(new ViewFactory() {\n public View makeView() {\n ImageView myView = new ImageView(getApplicationContext());\n return myView;\n }\n}" }, { "code": null, "e": 5107, "s": 4884, "text": "The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below −" }, { "code": null, "e": 5266, "s": 5107, "text": "Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);\nimageSwitcher.setInAnimation(in);\nimageSwitcher.setOutAnimation(out); " }, { "code": null, "e": 5455, "s": 5266, "text": "The method setInAnimaton sets the animation of the appearance of the object on the screen whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation object." }, { "code": null, "e": 5566, "s": 5455, "text": "Apart from these methods, there are other methods defined in the ImageSwitcher class. They are defined below −" }, { "code": null, "e": 5602, "s": 5566, "text": "setImageDrawable(Drawable drawable)" }, { "code": null, "e": 5679, "s": 5602, "text": "Sets an image with image switcher. The image is passed in the form of bitmap" }, { "code": null, "e": 5707, "s": 5679, "text": "setImageResource(int resid)" }, { "code": null, "e": 5788, "s": 5707, "text": "Sets an image with image switcher. The image is passed in the form of integer id" }, { "code": null, "e": 5809, "s": 5788, "text": "setImageURI(Uri uri)" }, { "code": null, "e": 5883, "s": 5809, "text": "Sets an image with image switcher. THe image is passed in the form of URI" }, { "code": null, "e": 5934, "s": 5883, "text": "ImageSwitcher(Context context, AttributeSet attrs)" }, { "code": null, "e": 6025, "s": 5934, "text": "Returns an image switcher object with already setting some attributes passed in the method" }, { "code": null, "e": 6083, "s": 6025, "text": "onInitializeAccessibilityEvent (AccessibilityEvent event)" }, { "code": null, "e": 6176, "s": 6083, "text": "Initializes an AccessibilityEvent with information about this View which is the event source" }, { "code": null, "e": 6239, "s": 6176, "text": "onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)" }, { "code": null, "e": 6309, "s": 6239, "text": "Initializes an AccessibilityNodeInfo with information about this view" }, { "code": null, "e": 6481, "s": 6309, "text": "The below example demonstrates some of the image switcher effects on the bitmap. It crates a basic application that allows you to view the animation effects on the images." }, { "code": null, "e": 6557, "s": 6481, "text": "To experiment with this example , you need to run this on an actual device." }, { "code": null, "e": 6640, "s": 6557, "text": "Following is the content of the modified main activity file src/MainActivity.java." }, { "code": null, "e": 8439, "s": 6640, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.app.ActionBar.LayoutParams;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.ImageSwitcher;\nimport android.widget.ImageView;\nimport android.widget.Toast;\nimport android.widget.ViewSwitcher.ViewFactory;\n\npublic class MainActivity extends Activity {\n private ImageSwitcher sw;\n private Button b1,b2;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1 = (Button) findViewById(R.id.button);\n b2 = (Button) findViewById(R.id.button2);\n\n sw = (ImageSwitcher) findViewById(R.id.imageSwitcher);\n sw.setFactory(new ViewFactory() {\n @Override\n public View makeView() {\n ImageView myView = new ImageView(getApplicationContext());\n myView.setScaleType(ImageView.ScaleType.FIT_CENTER);\n myView.setLayoutParams(new \n ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,\n LayoutParams.WRAP_CONTENT));\n return myView;\n }\n });\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"previous Image\",\n Toast.LENGTH_LONG).show();\n sw.setImageResource(R.drawable.abc);\n }\n });\n\n b2.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Next Image\",\n Toast.LENGTH_LONG).show();\n sw.setImageResource(R.drawable.tp);\n }\n });\n }\n}" }, { "code": null, "e": 8514, "s": 8439, "text": "Following is the modified content of the xml res/layout/activity_main.xml." }, { "code": null, "e": 10549, "s": 8514, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView android:text=\"Gestures Example\" \n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageSwitcher\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageSwitcher\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"168dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/left\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/right\"\n android:id=\"@+id/button2\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignLeft=\"@+id/button\"\n android:layout_alignStart=\"@+id/button\" />\n \n</RelativeLayout>" }, { "code": null, "e": 10595, "s": 10549, "text": "Following is the content of Strings.xml file." }, { "code": null, "e": 10767, "s": 10595, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n <string name=\"left\"><![CDATA[<]]></string>\n <string name=\"right\"><![CDATA[>]]></string>\n</resources>" }, { "code": null, "e": 10821, "s": 10767, "text": "Following is the content of AndroidManifest.xml file." }, { "code": null, "e": 11562, "s": 10821, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\"\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 11956, "s": 11562, "text": "Let's try to run your application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 12031, "s": 11956, "text": "Now if you will look at your device screen , you will see the two buttons." }, { "code": null, "e": 12158, "s": 12031, "text": "Now just select the upper button that right arrow. An image would appear from right and move towards left. It is shown below −" }, { "code": null, "e": 12269, "s": 12158, "text": "Now tap on the below button, that will bring back the previous image with some transition. It is shown below −" }, { "code": null, "e": 12304, "s": 12269, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12316, "s": 12304, "text": " Aditya Dua" }, { "code": null, "e": 12351, "s": 12316, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12365, "s": 12351, "text": " Sharad Kumar" }, { "code": null, "e": 12397, "s": 12365, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 12414, "s": 12397, "text": " Abhilash Nelson" }, { "code": null, "e": 12449, "s": 12414, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12466, "s": 12449, "text": " Abhilash Nelson" }, { "code": null, "e": 12501, "s": 12466, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12518, "s": 12501, "text": " Abhilash Nelson" }, { "code": null, "e": 12551, "s": 12518, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 12568, "s": 12551, "text": " Abhilash Nelson" }, { "code": null, "e": 12575, "s": 12568, "text": " Print" }, { "code": null, "e": 12586, "s": 12575, "text": " Add Notes" } ]
Python Program to convert Kilometers to Miles
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given distance in kilometers and we need to convert it into miles As we know that 1 kilometer equals 0.62137 miles. Miles = kilometer * 0.62137 Now let’s observe the concept in the implementation below− Live Demo kilometers = 5.5 # conversion factor as 1 km = 0.621371 miles conv = 0.621371 # calculation miles = kilometers * conv print(kilometers,"kilometers is equal to ",miles,"miles") 5.5 kilometers is equal to 3.4175405 miles All the variables are declared in the local scope and their references are seen in the figure above. In this article, we have learned about the conversion of distance given in kilometers into miles.
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1243, "s": 1150, "text": "Problem statement − We are given distance in kilometers and we need to convert it into miles" }, { "code": null, "e": 1293, "s": 1243, "text": "As we know that 1 kilometer equals 0.62137 miles." }, { "code": null, "e": 1321, "s": 1293, "text": "Miles = kilometer * 0.62137" }, { "code": null, "e": 1380, "s": 1321, "text": "Now let’s observe the concept in the implementation below−" }, { "code": null, "e": 1391, "s": 1380, "text": " Live Demo" }, { "code": null, "e": 1567, "s": 1391, "text": "kilometers = 5.5\n# conversion factor as 1 km = 0.621371 miles\nconv = 0.621371\n# calculation\nmiles = kilometers * conv\nprint(kilometers,\"kilometers is equal to \",miles,\"miles\")" }, { "code": null, "e": 1610, "s": 1567, "text": "5.5 kilometers is equal to 3.4175405 miles" }, { "code": null, "e": 1711, "s": 1610, "text": "All the variables are declared in the local scope and their references are seen in the figure above." }, { "code": null, "e": 1809, "s": 1711, "text": "In this article, we have learned about the conversion of distance given in kilometers into miles." } ]
Batch Script - START
This batch command starts a program in new window, or opens a document. START “programname” @echo off start notepad.exe When the batch file is executed, a new notepad windows will start. Print Add Notes Bookmark this page
[ { "code": null, "e": 2241, "s": 2169, "text": "This batch command starts a program in new window, or opens a document." }, { "code": null, "e": 2262, "s": 2241, "text": "START “programname”\n" }, { "code": null, "e": 2290, "s": 2262, "text": "@echo off\nstart notepad.exe" }, { "code": null, "e": 2357, "s": 2290, "text": "When the batch file is executed, a new notepad windows will start." }, { "code": null, "e": 2364, "s": 2357, "text": " Print" }, { "code": null, "e": 2375, "s": 2364, "text": " Add Notes" } ]
C Program to list all files and sub-directories in a directory
Here, we are given a directory. Our task is to create a C program to list all files and sub-directories in a directory. The directory is a place/area/location where a set of the file(s) will be stored. Subdirectory is a directory inside the root directory, in turn, it can have another sub-directory in it. In C programming language you can list all files and sub-directories of a directory easily. The below program will illustrate how to list all files and sub-directories in a directory. //C program to list all files and sub-directories in a directory Live Demo #include <stdio.h> #include <dirent.h> int main(void){ struct dirent *files; DIR *dir = opendir("."); if (dir == NULL){ printf("Directory cannot be opened!" ); return 0; } while ((files = readdir(dir)) != NULL) printf("%s\n", files->d_name); closedir(dir); return 0; } cprograms .. prog1.c prog2.c prog3.c ... prog41.c This will return all files and sub-directory of the current directory.
[ { "code": null, "e": 1182, "s": 1062, "text": "Here, we are given a directory. Our task is to create a C program to list all files and sub-directories in a directory." }, { "code": null, "e": 1264, "s": 1182, "text": "The directory is a place/area/location where a set of the file(s) will be stored." }, { "code": null, "e": 1369, "s": 1264, "text": "Subdirectory is a directory inside the root directory, in turn, it can have another sub-directory in it." }, { "code": null, "e": 1553, "s": 1369, "text": "In C programming language you can list all files and sub-directories of a directory easily. The below program will illustrate how to list all files and sub-directories in a directory." }, { "code": null, "e": 1618, "s": 1553, "text": "//C program to list all files and sub-directories in a directory" }, { "code": null, "e": 1629, "s": 1618, "text": " Live Demo" }, { "code": null, "e": 1934, "s": 1629, "text": "#include <stdio.h>\n#include <dirent.h>\nint main(void){\n struct dirent *files;\n DIR *dir = opendir(\".\");\n if (dir == NULL){\n printf(\"Directory cannot be opened!\" );\n return 0;\n }\n while ((files = readdir(dir)) != NULL)\n printf(\"%s\\n\", files->d_name);\n closedir(dir);\n return 0;\n}" }, { "code": null, "e": 2055, "s": 1934, "text": "cprograms\n..\nprog1.c\nprog2.c\nprog3.c\n...\nprog41.c\nThis will return all files and sub-directory of the current directory." } ]
Creating Sequential Stream from an Iterator in Java - GeeksforGeeks
11 Dec, 2018 Iterators, in Java, are used in Collection Framework to retrieve elements one by one. A stream in Java is a pipeline of objects from an array or a collection data source. A sequential stream is one in which the objects are pipelined in a single stream on the same processing system. Other types of stream include Parallel stream in which the objects are pipelined on multi-processing system. Hence often it is required to use the iterator as a sequential stream. There are many ways in which it can be done, these are: Using Spliterator: Spliterator like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel or a generator function.Methods used:ClassModifier and TypeMethodDescriptionSpliteratorsstatic <T> Spliterator<T>spliteratorUnknownSize(Iterator<? extends T> iterator, int characteristics)Creates a Spliterator using a given Iterator as the source of elements, with no initial size estimate.StreamSupportstatic <T> Stream<T>stream(Spliterator<T> spliterator, boolean parallel)Creates a new sequential or parallel Stream from a Spliterator.Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not.Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter "false" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S] Using Iterable.Spliterator(): Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator.So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter "false" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S] Using Spliterator: Spliterator like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel or a generator function.Methods used:ClassModifier and TypeMethodDescriptionSpliteratorsstatic <T> Spliterator<T>spliteratorUnknownSize(Iterator<? extends T> iterator, int characteristics)Creates a Spliterator using a given Iterator as the source of elements, with no initial size estimate.StreamSupportstatic <T> Stream<T>stream(Spliterator<T> spliterator, boolean parallel)Creates a new sequential or parallel Stream from a Spliterator.Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not.Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter "false" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S] Methods used: Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not. Program: // Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter "false" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }} Sequential Stream : [G, E, E, K, S] Using Iterable.Spliterator(): Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator.So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter "false" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S] So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator(). Program: // Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter "false" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList("G", "E", "E", "K", "S").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println("Sequential Stream : " + stream.collect(Collectors.toList())); }} Sequential Stream : [G, E, E, K, S] Java - util package Java-Iterable Java-Iterator java-stream Java-Stream-programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java LinkedList in Java ArrayList in Java PriorityQueue in Java How to iterate any Map in Java Queue Interface In Java Stack Class in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 24139, "s": 24111, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24225, "s": 24139, "text": "Iterators, in Java, are used in Collection Framework to retrieve elements one by one." }, { "code": null, "e": 24531, "s": 24225, "text": "A stream in Java is a pipeline of objects from an array or a collection data source. A sequential stream is one in which the objects are pipelined in a single stream on the same processing system. Other types of stream include Parallel stream in which the objects are pipelined on multi-processing system." }, { "code": null, "e": 24658, "s": 24531, "text": "Hence often it is required to use the iterator as a sequential stream. There are many ways in which it can be done, these are:" }, { "code": null, "e": 28259, "s": 24658, "text": "Using Spliterator: Spliterator like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel or a generator function.Methods used:ClassModifier and TypeMethodDescriptionSpliteratorsstatic <T> Spliterator<T>spliteratorUnknownSize(Iterator<? extends T> iterator, int characteristics)Creates a Spliterator using a given Iterator as the source of elements, with no initial size estimate.StreamSupportstatic <T> Stream<T>stream(Spliterator<T> spliterator, boolean parallel)Creates a new sequential or parallel Stream from a Spliterator.Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not.Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter \"false\" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S]\nUsing Iterable.Spliterator(): Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator.So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter \"false\" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S]\n" }, { "code": null, "e": 30433, "s": 28259, "text": "Using Spliterator: Spliterator like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel or a generator function.Methods used:ClassModifier and TypeMethodDescriptionSpliteratorsstatic <T> Spliterator<T>spliteratorUnknownSize(Iterator<? extends T> iterator, int characteristics)Creates a Spliterator using a given Iterator as the source of elements, with no initial size estimate.StreamSupportstatic <T> Stream<T>stream(Spliterator<T> spliterator, boolean parallel)Creates a new sequential or parallel Stream from a Spliterator.Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not.Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter \"false\" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S]\n" }, { "code": null, "e": 30447, "s": 30433, "text": "Methods used:" }, { "code": null, "e": 30916, "s": 30447, "text": "Explanation: Spliterator acts as the intermediate while creating Sequential Stream from Iterator. The Iterator is first converted to Spliterator with the help of Spliterators.spliteratorUnknownSize(). Find the method description of this below. The Spliterator is then converted to Sequential Stream with the help of StreamSupport.stream() function. The second parameter of this function takes the boolean value to whether the stream to be generated is Parallel or not." }, { "code": null, "e": 30925, "s": 30916, "text": "Program:" }, { "code": "// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // convert the iterator into a Spliterator Spliterator<T> spitr = Spliterators.spliteratorUnknownSize( itr, Spliterator.NONNULL); // Convert spliterator into a sequential stream // The second parameter \"false\" passess whether // the stream is to be created parallel or not return StreamSupport.stream(spitr, false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}", "e": 32000, "s": 30925, "text": null }, { "code": null, "e": 32037, "s": 32000, "text": "Sequential Stream : [G, E, E, K, S]\n" }, { "code": null, "e": 33465, "s": 32037, "text": "Using Iterable.Spliterator(): Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator.So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().Program:// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter \"false\" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}Output:Sequential Stream : [G, E, E, K, S]\n" }, { "code": null, "e": 33607, "s": 33465, "text": "So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator()." }, { "code": null, "e": 33616, "s": 33607, "text": "Program:" }, { "code": "// Java program to create a Sequential Stream// from an Iterator import java.util.*;import java.util.stream.*; class GfG { // Function to create a sequential Stream // from an Iterator public static <T> Stream<T> iteratorToSequentialStream(Iterator<T> itr) { // Get an iterable from itr Iterable<T> itb = () -> itr; // Get spliterator() from iterable and then // Convert into a sequential stream. // The second parameter \"false\" passess whether the // stream is to be created parallel or not return StreamSupport.stream(itb.spliterator(), false); } public static void main(String[] args) { Iterator<String> iterator = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"S\").iterator(); Stream<String> stream = iteratorToSequentialStream(iterator); System.out.println(\"Sequential Stream : \" + stream.collect(Collectors.toList())); }}", "e": 34624, "s": 33616, "text": null }, { "code": null, "e": 34661, "s": 34624, "text": "Sequential Stream : [G, E, E, K, S]\n" }, { "code": null, "e": 34681, "s": 34661, "text": "Java - util package" }, { "code": null, "e": 34695, "s": 34681, "text": "Java-Iterable" }, { "code": null, "e": 34709, "s": 34695, "text": "Java-Iterator" }, { "code": null, "e": 34721, "s": 34709, "text": "java-stream" }, { "code": null, "e": 34742, "s": 34721, "text": "Java-Stream-programs" }, { "code": null, "e": 34747, "s": 34742, "text": "Java" }, { "code": null, "e": 34752, "s": 34747, "text": "Java" }, { "code": null, "e": 34850, "s": 34752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34859, "s": 34850, "text": "Comments" }, { "code": null, "e": 34872, "s": 34859, "text": "Old Comments" }, { "code": null, "e": 34904, "s": 34872, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34923, "s": 34904, "text": "Overriding in Java" }, { "code": null, "e": 34955, "s": 34923, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34974, "s": 34955, "text": "LinkedList in Java" }, { "code": null, "e": 34992, "s": 34974, "text": "ArrayList in Java" }, { "code": null, "e": 35014, "s": 34992, "text": "PriorityQueue in Java" }, { "code": null, "e": 35045, "s": 35014, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35069, "s": 35045, "text": "Queue Interface In Java" }, { "code": null, "e": 35089, "s": 35069, "text": "Stack Class in Java" } ]
Introducing Bamboolib — a GUI for Pandas | by Dario Radečić | Towards Data Science
He states, and I quote: Our goal is to help people quickly learn and work with pandas, and we want to onboard the next generation of python data scientists. I have to admit, I was skeptical at first, mainly because I’m not a big fan of GUI tools and drag & drop principle in general. Still, I’ve opened the URL and watched the introduction video. It was one of those rare times when I was legitimately intrigued. From there I’ve quickly responded to Tobias, and he kindly offered me to test out the library and see if I liked it. How was it? Well, you’ll have to keep reading to find the answer to that. So let’s get started. In a world where such amazing libraries like Numpy and Pandas are free to use, this question may not even pop in your head. However, it should, because not all versions of Bamboolib are free. If you don’t mind sharing your work with others, then yeah, it’s free to use, but if that poses a problem then it will set you back at least $10 a month which might be a bummer for the average users. Down below is the full pricing list: As the developer of the library stated, Bamboolib is designed to help you learn Pandas, so I don’t see a problem with going with the free option — most likely you won’t be working on some top-secret project if just starting out. This review will, however, be based on the private version of the library, as that’s the one Tobias gave access to me. With that being said, this article is by no means written with the idea of persuading you to buy the license, it only provides my personal opinion. Before jumping into the good stuff, you’ll need to install the library first. The first and most obvious thing to do is pip install: pip install bamboolib However, there’s a lot more to do if you want this thing fully working. It is designed to be a Jupyter Lab extension (or Jupyter Notebook if you still use those), so we’ll need to set up a couple of things there also. In a command line type the following: jupyter nbextension enable --py qgrid --sys-prefixjupyter nbextension enable --py widgetsnbextension --sys-prefixjupyter nbextension install --py bamboolib --sys-prefixjupyter nbextension enable --py bamboolib --sys-prefix Now you’ll need to find the major version of Jupyter Lab installed on your machine. You can obtain it with the following command: jupyter labextension list Mine is “1.0”, but yours can be anything, so here’s a generic version of the next command you’ll need to execute: jupyter labextension install @jupyter-widgets/jupyterlab-manager@MAJOR_VERSION.MINOR_VERSION --no-build Note that you need to replace “MAJOR_VERSION.MINOR_VERSION” with the version number, which is “1.0” in my case. A couple of commands more and you’re ready to rock: jupyter labextension install @8080labs/[email protected] --no-buildjupyter labextension install plotlywidget --no-buildjupyter labextension install jupyterlab-plotly --no-buildjupyter labextension install bamboolib --no-buildjupyter lab build --minimize=False That’ it. Now you can start Juypter Lab and we can dive into the good stuff. Once in Jupyter, you can import Bamboolib and Pandas, and then use Pandas to load in some dataset: Here’s how you’d use the library to view the dataset: That’s not gonna work the first time you’re using the library. You’ll need to activate it, so make sure to have the license key somewhere near: Once you’ve entered the email and license key, you should get the following message indicating that everything went well: Great, now you can once again execute the previous cell. Immediately you’ll see an unfamiliar, but friendly-looking interface: Now everything is good to go, and we can dive into some basic functionalities. It was a lot of work to get to this point, but trust me, it was worth it! One of the most common everyday tasks of any data analyst/scientist is data filtering. Basically you want to keep only a subset of data that’s relevant to you in a given moment. To start filtering with Bamboolib, click on the Filter button. A side menu like the one below should pop up. I’ve decided to filter by the “Age” column, and keep only the rows where the value of “Age” is less than 18: Once you press Execute, you’ll see the actions took place immediately: That’s great! But what more can you do? Another one of those common everyday tasks is to replace string values with the respective numerical alternative. This dataset is perfect to demonstrate value replacement because we can easily replace string values in the “Sex” column with numeric ones. To begin, hit the Replace value button and specify the column, the value you want to replace and what you want to replace it with: And once the Execute button is hit: Fantastic! You can do the same for the “female” option, but it’s up to you whether you want to do it or not. Yes, you can also perform aggregations! To get started, click on the Aggregate/Group by button and specify what should be done in the side menu. I’ve decided to group by “Pclass”, because I want to see the total number of survivors per passenger class: That will yield the following output: Awesome! Let’s explore one more thing before wrapping up. Many times when preparing data for machine learning you’ll want to create dummy variables, ergo create a new column per unique value of a given attribute. It’s a good idea to do so because many machine learning algorithms can’t work with text data. To implement that logic via Bamboolib, hit the OneHotEncoder button. I’ve decided to create dummy variables from the “Embarked” attribute because it has 3 distinct values and you can’t state that one is better than the other. Also, make sure to remove the first dummy to avoid collinearity issues (having variable which is a perfect predictor for some other variable): Executing will create two new columns in the dataset, just as you would expect: That’s nice, I’ve done my transformations, but what’s next? It was all fun and games until now, but sooner or later you’ll notice the operations don’t act in place — ergo the dataset will not get modified if you don’t explicitly specify it. That’s not a bug, as it enables you to play around without messing the original dataset. What Bamboolib will do, however, it will generate Python code for achieving the desired transformations. To get the code, first, click on the Export button: Now specify how do you want it exported — I’ve selected the first option: And it will finally give you the code which you can copy and apply to the dataset: Until this point, I showcased briefly the main functionalities of Bamboolib — by no means was it exhaustive tutorial — just wanted to show you the idea behind it. The question remains, is it worth the money? That is if you decide to go with the paid route. You can still use it for free, provided that you don’t mind sharing your work with others. The library by itself is worth checking out for two main reasons: It provides a great way to learn Pandas — it’s much more easy to learn by doing than by reading, and a GUI tool like this will most certainly only help youIt’s great for playing around with data — let’s face it, there are times when you know what you want to do, but you just don’t know how to implement it in code — Bamboolib can assist It provides a great way to learn Pandas — it’s much more easy to learn by doing than by reading, and a GUI tool like this will most certainly only help you It’s great for playing around with data — let’s face it, there are times when you know what you want to do, but you just don’t know how to implement it in code — Bamboolib can assist Keep in mind — you won’t get any additional features with the paid version — the only real benefit is that your work will be private and that there’s an option for commercial use. Even if you’re not ready to grab your credit card just yet, it can’t harm you to try out the free version and see if it’s something you can benefit from. Thanks for reading. Take care. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 196, "s": 172, "text": "He states, and I quote:" }, { "code": null, "e": 329, "s": 196, "text": "Our goal is to help people quickly learn and work with pandas, and we want to onboard the next generation of python data scientists." }, { "code": null, "e": 519, "s": 329, "text": "I have to admit, I was skeptical at first, mainly because I’m not a big fan of GUI tools and drag & drop principle in general. Still, I’ve opened the URL and watched the introduction video." }, { "code": null, "e": 585, "s": 519, "text": "It was one of those rare times when I was legitimately intrigued." }, { "code": null, "e": 702, "s": 585, "text": "From there I’ve quickly responded to Tobias, and he kindly offered me to test out the library and see if I liked it." }, { "code": null, "e": 798, "s": 702, "text": "How was it? Well, you’ll have to keep reading to find the answer to that. So let’s get started." }, { "code": null, "e": 990, "s": 798, "text": "In a world where such amazing libraries like Numpy and Pandas are free to use, this question may not even pop in your head. However, it should, because not all versions of Bamboolib are free." }, { "code": null, "e": 1227, "s": 990, "text": "If you don’t mind sharing your work with others, then yeah, it’s free to use, but if that poses a problem then it will set you back at least $10 a month which might be a bummer for the average users. Down below is the full pricing list:" }, { "code": null, "e": 1456, "s": 1227, "text": "As the developer of the library stated, Bamboolib is designed to help you learn Pandas, so I don’t see a problem with going with the free option — most likely you won’t be working on some top-secret project if just starting out." }, { "code": null, "e": 1723, "s": 1456, "text": "This review will, however, be based on the private version of the library, as that’s the one Tobias gave access to me. With that being said, this article is by no means written with the idea of persuading you to buy the license, it only provides my personal opinion." }, { "code": null, "e": 1801, "s": 1723, "text": "Before jumping into the good stuff, you’ll need to install the library first." }, { "code": null, "e": 1856, "s": 1801, "text": "The first and most obvious thing to do is pip install:" }, { "code": null, "e": 1878, "s": 1856, "text": "pip install bamboolib" }, { "code": null, "e": 2096, "s": 1878, "text": "However, there’s a lot more to do if you want this thing fully working. It is designed to be a Jupyter Lab extension (or Jupyter Notebook if you still use those), so we’ll need to set up a couple of things there also." }, { "code": null, "e": 2134, "s": 2096, "text": "In a command line type the following:" }, { "code": null, "e": 2357, "s": 2134, "text": "jupyter nbextension enable --py qgrid --sys-prefixjupyter nbextension enable --py widgetsnbextension --sys-prefixjupyter nbextension install --py bamboolib --sys-prefixjupyter nbextension enable --py bamboolib --sys-prefix" }, { "code": null, "e": 2487, "s": 2357, "text": "Now you’ll need to find the major version of Jupyter Lab installed on your machine. You can obtain it with the following command:" }, { "code": null, "e": 2513, "s": 2487, "text": "jupyter labextension list" }, { "code": null, "e": 2627, "s": 2513, "text": "Mine is “1.0”, but yours can be anything, so here’s a generic version of the next command you’ll need to execute:" }, { "code": null, "e": 2731, "s": 2627, "text": "jupyter labextension install @jupyter-widgets/jupyterlab-manager@MAJOR_VERSION.MINOR_VERSION --no-build" }, { "code": null, "e": 2843, "s": 2731, "text": "Note that you need to replace “MAJOR_VERSION.MINOR_VERSION” with the version number, which is “1.0” in my case." }, { "code": null, "e": 2895, "s": 2843, "text": "A couple of commands more and you’re ready to rock:" }, { "code": null, "e": 3149, "s": 2895, "text": "jupyter labextension install @8080labs/[email protected] --no-buildjupyter labextension install plotlywidget --no-buildjupyter labextension install jupyterlab-plotly --no-buildjupyter labextension install bamboolib --no-buildjupyter lab build --minimize=False" }, { "code": null, "e": 3226, "s": 3149, "text": "That’ it. Now you can start Juypter Lab and we can dive into the good stuff." }, { "code": null, "e": 3325, "s": 3226, "text": "Once in Jupyter, you can import Bamboolib and Pandas, and then use Pandas to load in some dataset:" }, { "code": null, "e": 3379, "s": 3325, "text": "Here’s how you’d use the library to view the dataset:" }, { "code": null, "e": 3523, "s": 3379, "text": "That’s not gonna work the first time you’re using the library. You’ll need to activate it, so make sure to have the license key somewhere near:" }, { "code": null, "e": 3645, "s": 3523, "text": "Once you’ve entered the email and license key, you should get the following message indicating that everything went well:" }, { "code": null, "e": 3772, "s": 3645, "text": "Great, now you can once again execute the previous cell. Immediately you’ll see an unfamiliar, but friendly-looking interface:" }, { "code": null, "e": 3925, "s": 3772, "text": "Now everything is good to go, and we can dive into some basic functionalities. It was a lot of work to get to this point, but trust me, it was worth it!" }, { "code": null, "e": 4103, "s": 3925, "text": "One of the most common everyday tasks of any data analyst/scientist is data filtering. Basically you want to keep only a subset of data that’s relevant to you in a given moment." }, { "code": null, "e": 4166, "s": 4103, "text": "To start filtering with Bamboolib, click on the Filter button." }, { "code": null, "e": 4321, "s": 4166, "text": "A side menu like the one below should pop up. I’ve decided to filter by the “Age” column, and keep only the rows where the value of “Age” is less than 18:" }, { "code": null, "e": 4392, "s": 4321, "text": "Once you press Execute, you’ll see the actions took place immediately:" }, { "code": null, "e": 4432, "s": 4392, "text": "That’s great! But what more can you do?" }, { "code": null, "e": 4686, "s": 4432, "text": "Another one of those common everyday tasks is to replace string values with the respective numerical alternative. This dataset is perfect to demonstrate value replacement because we can easily replace string values in the “Sex” column with numeric ones." }, { "code": null, "e": 4817, "s": 4686, "text": "To begin, hit the Replace value button and specify the column, the value you want to replace and what you want to replace it with:" }, { "code": null, "e": 4853, "s": 4817, "text": "And once the Execute button is hit:" }, { "code": null, "e": 4962, "s": 4853, "text": "Fantastic! You can do the same for the “female” option, but it’s up to you whether you want to do it or not." }, { "code": null, "e": 5107, "s": 4962, "text": "Yes, you can also perform aggregations! To get started, click on the Aggregate/Group by button and specify what should be done in the side menu." }, { "code": null, "e": 5215, "s": 5107, "text": "I’ve decided to group by “Pclass”, because I want to see the total number of survivors per passenger class:" }, { "code": null, "e": 5253, "s": 5215, "text": "That will yield the following output:" }, { "code": null, "e": 5311, "s": 5253, "text": "Awesome! Let’s explore one more thing before wrapping up." }, { "code": null, "e": 5560, "s": 5311, "text": "Many times when preparing data for machine learning you’ll want to create dummy variables, ergo create a new column per unique value of a given attribute. It’s a good idea to do so because many machine learning algorithms can’t work with text data." }, { "code": null, "e": 5929, "s": 5560, "text": "To implement that logic via Bamboolib, hit the OneHotEncoder button. I’ve decided to create dummy variables from the “Embarked” attribute because it has 3 distinct values and you can’t state that one is better than the other. Also, make sure to remove the first dummy to avoid collinearity issues (having variable which is a perfect predictor for some other variable):" }, { "code": null, "e": 6009, "s": 5929, "text": "Executing will create two new columns in the dataset, just as you would expect:" }, { "code": null, "e": 6069, "s": 6009, "text": "That’s nice, I’ve done my transformations, but what’s next?" }, { "code": null, "e": 6250, "s": 6069, "text": "It was all fun and games until now, but sooner or later you’ll notice the operations don’t act in place — ergo the dataset will not get modified if you don’t explicitly specify it." }, { "code": null, "e": 6444, "s": 6250, "text": "That’s not a bug, as it enables you to play around without messing the original dataset. What Bamboolib will do, however, it will generate Python code for achieving the desired transformations." }, { "code": null, "e": 6496, "s": 6444, "text": "To get the code, first, click on the Export button:" }, { "code": null, "e": 6570, "s": 6496, "text": "Now specify how do you want it exported — I’ve selected the first option:" }, { "code": null, "e": 6653, "s": 6570, "text": "And it will finally give you the code which you can copy and apply to the dataset:" }, { "code": null, "e": 6816, "s": 6653, "text": "Until this point, I showcased briefly the main functionalities of Bamboolib — by no means was it exhaustive tutorial — just wanted to show you the idea behind it." }, { "code": null, "e": 6861, "s": 6816, "text": "The question remains, is it worth the money?" }, { "code": null, "e": 7067, "s": 6861, "text": "That is if you decide to go with the paid route. You can still use it for free, provided that you don’t mind sharing your work with others. The library by itself is worth checking out for two main reasons:" }, { "code": null, "e": 7405, "s": 7067, "text": "It provides a great way to learn Pandas — it’s much more easy to learn by doing than by reading, and a GUI tool like this will most certainly only help youIt’s great for playing around with data — let’s face it, there are times when you know what you want to do, but you just don’t know how to implement it in code — Bamboolib can assist" }, { "code": null, "e": 7561, "s": 7405, "text": "It provides a great way to learn Pandas — it’s much more easy to learn by doing than by reading, and a GUI tool like this will most certainly only help you" }, { "code": null, "e": 7744, "s": 7561, "text": "It’s great for playing around with data — let’s face it, there are times when you know what you want to do, but you just don’t know how to implement it in code — Bamboolib can assist" }, { "code": null, "e": 7924, "s": 7744, "text": "Keep in mind — you won’t get any additional features with the paid version — the only real benefit is that your work will be private and that there’s an option for commercial use." }, { "code": null, "e": 8078, "s": 7924, "text": "Even if you’re not ready to grab your credit card just yet, it can’t harm you to try out the free version and see if it’s something you can benefit from." }, { "code": null, "e": 8109, "s": 8078, "text": "Thanks for reading. Take care." } ]
Python 3 - String replace() Method
The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. Following is the syntax for replace() method − str.replace(old, new[, max]) old − This is old substring to be replaced. old − This is old substring to be replaced. new − This is new substring, which would replace old substring. new − This is new substring, which would replace old substring. max − If this optional argument max is given, only the first count occurrences are replaced. max − If this optional argument max is given, only the first count occurrences are replaced. This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced. The following example shows the usage of replace() method. #!/usr/bin/python3 str = "this is string example....wow!!! this is really string" print (str.replace("is", "was")) print (str.replace("is", "was", 3)) When we run above program, it produces the following result − thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string 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": 2509, "s": 2340, "text": "The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max." }, { "code": null, "e": 2556, "s": 2509, "text": "Following is the syntax for replace() method −" }, { "code": null, "e": 2586, "s": 2556, "text": "str.replace(old, new[, max])\n" }, { "code": null, "e": 2630, "s": 2586, "text": "old − This is old substring to be replaced." }, { "code": null, "e": 2674, "s": 2630, "text": "old − This is old substring to be replaced." }, { "code": null, "e": 2738, "s": 2674, "text": "new − This is new substring, which would replace old substring." }, { "code": null, "e": 2802, "s": 2738, "text": "new − This is new substring, which would replace old substring." }, { "code": null, "e": 2895, "s": 2802, "text": "max − If this optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 2988, "s": 2895, "text": "max − If this optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 3170, "s": 2988, "text": "This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 3229, "s": 3170, "text": "The following example shows the usage of replace() method." }, { "code": null, "e": 3381, "s": 3229, "text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!! this is really string\"\nprint (str.replace(\"is\", \"was\"))\nprint (str.replace(\"is\", \"was\", 3))" }, { "code": null, "e": 3443, "s": 3381, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3561, "s": 3443, "text": "thwas was string example....wow!!! thwas was really string\nthwas was string example....wow!!! thwas is really string\n" }, { "code": null, "e": 3598, "s": 3561, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3614, "s": 3598, "text": " Malhar Lathkar" }, { "code": null, "e": 3647, "s": 3614, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3666, "s": 3647, "text": " Arnab Chakraborty" }, { "code": null, "e": 3701, "s": 3666, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3723, "s": 3701, "text": " In28Minutes Official" }, { "code": null, "e": 3757, "s": 3723, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3785, "s": 3757, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3820, "s": 3785, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3834, "s": 3820, "text": " Lets Kode It" }, { "code": null, "e": 3867, "s": 3834, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3884, "s": 3867, "text": " Abhilash Nelson" }, { "code": null, "e": 3891, "s": 3884, "text": " Print" }, { "code": null, "e": 3902, "s": 3891, "text": " Add Notes" } ]
Create AI for your Own Board Game From Scratch — AlphaZero-Part 3 | by Haryo Akbarianto Wibowo | Towards Data Science
Hello everyone, welcome to the part 3 of making AI on the EvoPawness (Temporary Name). In this article, we will implement AlphaZero Algorithm to the game. This article will tell you a short summary of the AlphaZero and the implementation of the AlphaZero, albeit the simplified one. We will do it in a step by step. We will use some of terminology stated in the Part 1 such as Result Function, Possible Actions, and Terminal Function. The experiment is not done yet. It takes a long time to train the agent for this game, especially with a single computer. I’ve trained the agent for a day. Unfortunately, the agent is still not good enough. Even so, It has learnt a few strategy such as attacking the king continuously with knight if the knight can attack the king. I stopped training the agent to let my computer rest. I’m afraid my laptop will be broken if I force it to train more than a day. I also limited the hyperparameter of the AlphaZero to speed up the training time. I’m sorry for my limited resources on doing this experiment 😿. Even though the experiment is not complete, I will try to write how I implement the AlphaZero on this game. I hope that it will give an enlightenment to someone who want to learn about a reinforcement learning algorithm, AlphaZero, and implementing them to their game. I’ve made several changes on the game’s rule. The game still remains deterministic. This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article. I hope that my writing skill will increase by publishing this article and the content benefits you 😄. Brace yourself, It will be a long article. It has 25 minutes read ! RepositoryBrief description about AlphaZeroChanged RuleStepsComponents of AlphaZeroImplementation of AlphaZeroLesson LearnedConclusionAfterwords Repository Brief description about AlphaZero Changed Rule Steps Components of AlphaZero Implementation of AlphaZero Lesson Learned Conclusion Afterwords In case you start reading the progress of the game with this article, here is the repository: github.com I’ve added several changes to the repository: Add AlphaZero Implementation Reformat module or folder structure Change action representation key. Change the game model and controller to match the new rule Note : For now, I suggest that you do not try to train the model until I refactor and clean the code. And also, the code is still super messy, I will try to clean and refactor it as soon as possible. In the next Saturday, I will try to do it. Edit (3/12/2018) : I have cleaned the code. Now we have Config.py to edit the configuration. See main.py -h on how to launch the program. For further information, wait for me to edit the README.md tomorrow. Edit 2 (10/12/2018) : I’ve pushed the updated README.md AlphaZero is created by Deep Mind which is published in the following paper [Source 4]. What makes it special is that it can beat the best AI of chess and shogi under 24 hours training. It makes this algorithm is the best at that time on AI game. For further information you can see this article on how powerful this algorithm can be. It also don’t have human expertise as the input (except the rule of the game). It learns from zero to become the best AI game program which beat the best AI for the board game at that time. I also find that the algorithm is very simple yet astonishing. The algorithm will explore the possible paths that is promising with the current knowledge. The searched path will tell whether the current path is favourable or not. The score of how favourable it is is backed down and be used to be a consideration whether this path should be explored again. After the exploration on thinking the future possibility, take the action that is explored the most. It means that this action can be good if this path is often explored. At the end of the game, evaluate whether the path that it choose match to the outcome of the game. It tells us whether the knowledge misjudged the path that is chosen when exploring the possible future paths. The knowledge will be updated according to the outcome of the game. The AlphaZero need the game with perfect information (the game state is fully known to both players) and deterministic. Since this game has both of them, AlphaZero algorithm can be used to this game. In this article, we will simplify the architecture used on the paper. We will use a simplified AlphaZero implementation based on the article that I’ve read. In the implementation used by David Foster [Source 2], he uses 4 residual layers that is connected to a policy head and a value head. I used his architecture and change some hyperparameters. I also see the implementation of the AlphaZero in the [Source 1] and modify the implementation to suit this game. I follow the Monte Carlo Tree Search implementation in that article and change the implementation from using recursive to structure data tree. The implementation used on these articles are inline with the paper with some skipped parts. There are several steps that I skipped such as v resignation. In these two articles, they do not implement the stacked state. In this article, I implement the stacked state and using 140 planes as the input of the model. In this article, the implementation of the AlphaZero also haven’t implemented multi-thread MCTS by using virtual loss yet. The rune will spawn on 3 different positions. There are (on y, x axis) (4,0) , (4,4), and (4,8). The rune that spawn at (4,0) will raise 2 attack points. The rune that spawn at (4,4) will raise 2 health points. and the rune that spawn at (4,8) will raise 1 step points.Rune position that is occupied by a pawn when the time of rune spawn (every 5 turns) will not spawn the rune.Step, health, and attack points has a limit. 3 for steps, 20 for health, and 8 for attack points The rune will spawn on 3 different positions. There are (on y, x axis) (4,0) , (4,4), and (4,8). The rune that spawn at (4,0) will raise 2 attack points. The rune that spawn at (4,4) will raise 2 health points. and the rune that spawn at (4,8) will raise 1 step points. Rune position that is occupied by a pawn when the time of rune spawn (every 5 turns) will not spawn the rune. Step, health, and attack points has a limit. 3 for steps, 20 for health, and 8 for attack points This article will implement the AlphaZero in the following order: Define the state representation for the input of the model. We use stacked state.Define the action representation for the game.Decide which side will be used to represent the state (black or white) for all players and define how to change the side.Define some identical states that can be used to increment the input of the modelDefine reward functionImplement the architecture of the neural network that is used to output the policy evaluationImplement the Monte Carlo Tree SearchAdd duel function to evaluate the best model. Define the state representation for the input of the model. We use stacked state. Define the action representation for the game. Decide which side will be used to represent the state (black or white) for all players and define how to change the side. Define some identical states that can be used to increment the input of the model Define reward function Implement the architecture of the neural network that is used to output the policy evaluation Implement the Monte Carlo Tree Search Add duel function to evaluate the best model. Before we go to this part, I suggest that if you haven’t read the part 1, read it. It will cover the rules of the game. We will see the representation state for the input of the neural network in this section. The input of the neural network is an image stack that represents the state. There are 28 input features used in the implementation. Here, we will use 5-step history (Note : in the paper of AlphaZero, the number of step history is 8. Here, this article will try a different number). From the number of step-history that we use, it means that there are 140 input features (28 X 5). The history will save the state representation at the previous turn. If we use 5-step history, given the state is at T turn, we will take T, T-1, T-2, T-3, T-4 state that will be stacked and become input for the neural network. Here are the input features: No 4–10, 13 use binary features whereas the others use frequency features. Since, the board is 9 x 9, if we have batch_size as the total instance of the input of neural network, we have (batch_size, 9, 9, 140) shape as the input of the neural network. So, we have 4 dimensional data as the input. For the code, you can see the get_representation_stack() function in the source code below: github.com In the source code, we will use AIElements class which contains the elements that we define in the part 1. We use deque as our data structure (like stack). Before we get the input representation of the neural network, we will stack the state, the state representation that we defined at Part 1, into a deque data structure with the desired max length (in this article, we set it to 5). Then we process the deque and change it into an input representation for the neural network. There are 5 type of actions that is available in the game. There are Activate, Promote, Move, Attack, and Skip. For the activate action, we need to select the pawn that want to be activated. We need the coordinates of the pawn. So we have 81 (9 x 9) different unique activate actions. Note: we have a different action key representation that is stated in the Part 1, the new representation is stated below: Action Key Representation for the activate action: a*y,xy : pawn's axis-yx : pawn's axis-xexample a*1,0 For the Promote action, we need to select the pawn that want to be promoted then select the possible choice to promote the pawn. We need the coordinates of the pawn . We have 9 x 9 different unique actions for selecting the possible pawn. There are 4 promoted pawn type (Queen, Rook, Bishop, Knight), so there are 324 (9 x 9 x 4) unique way to do the promote action. Action key representation for the promote action : p*y,x*choicey : pawn's axis-yx : pawn's axis-xchoice : promote choice, K for Knight, R for Rook, B for Bishop, and Q for Queenexample p*3,3*Q For the attack and move action, In this game, we have 7 type of pawns. The direction of the move has been defined in the Part 1. In the part 1, we have attack and move as separate action. In this article, we will combine the attack action and the move action into one (they don’t overlap, so we can combine them). We can see that the direction of move of Soldier, Rook, Bishop, and King is a subset of the Queen. It moves vertical, horizontal, and diagonally in the N, NE, E, SE, W, SW, W, and NW direction. Only knight has different moves. It moves in L-shape in all points direction of the compass. In summary, we have 2 type of moves, Queen and Knight. We have 2 steps on doing the action: selecting the pawn and selecting the legal move for the pawn based on the possible action. In this case, we have 81 (9 x 9) different actions for selecting the pawn. Then for selecting the legal move, we have 8 different actions for knight move’s type and 24 (8 x 3) for queen move’s type (Note : we have 3 as the limit of step points, so the queen move can consists of 24 type of move). The total of unique actions that can be made is 2592 (81 x 32) for selecting the legal move for attack and move action. Action Key Representation for the activate action: m*y1,x1*y2,x2y1 : selecting the pawn in axis-yx1 : selecting the pawn in axis-xy2 : direction of the move in axis-yx2 : direction of the move in axis-xExample m*0,1*2,1 (means that it will move from (0,1) to (2,2) Skip if the player cannot do anything. The action key representation for skip is skip The total of the unique action is 2998 (9 x 9 x 37 + 1) The action representation is used to encode the probability distribution that is used for selecting the action later on doing the Monte Carlo Tree Search (MCTS). Later, the action that is not possible to do in the state is masked and set the probability to 0 and re-normalize the probability distribution for the possible action. See the repository for the implementation on how to generate all possible action. I used LabelEncoder and OneHotEncoder provided in scikit-learn library to encode the action into One Hot Encoder. One Hot Encoder Class (see fit()): github.com Generate all unique actions (see action_spaces() function): github.com In the paper of AlphaZero, we need to orientate the perspective of the board to the current player. We must decide which side will be the perspective for both players. I choose white as the perspective or Point of View (POV) for both players. So if the current turn is black player, we will make the black player perspective become the white player perspective. If the current turn is white player, we will not change the player perspective. How can we do this? If this is a chess game, it will be easy. Just invert the color of the pieces. In this game, we cannot do that. The king is fixed at that position and cannot move. So, inverting the pieces will make the state invalid. So how can we do it? We need to mirror or reflect the position of each pawns. After that, invert the color of all the pawns. Here’s the pseudocode: def mirror(self, pawn): pawn.y = pawn.y - 4 # 4 is the center position of the board pawn.y *= -1 # after we move the center to 0, we mirror it pawn.y += 4 # Then we move the center point to 4 pawn.color = inverse(pawn.color) We do that to all of the pawns (King included). We have mirrored the position of the pawns. As we change the perspective of the board by changing the pawn’s position, we need to change the action too. We need to mirror the coordinates of the action and the direction if the action is move or attack. It’s similar to change the position of the pawn, we will change the coordinates of the action by mirroring the coordinates by manipulating the y-axis. For the direction, we only need to multiply the y-axis by -1. For example: {} = * means multiplication in this bracketoriginal = a*2,3mirror = a*{(2-4)*-1+4},3 = a*6,3original = m*1,0*1,0mirror = m*{(1-4)*-1+4,0}*{1*-1},0 = m*7,0*-1,0 That’s it how we change the perspective of the player. For the implementation, see all of the functions defined in this source code: github.com It’s essentially the same as the pseudocode, but in OOP way. We will change the attributes of all the object of pawns. The mirror of the action is also defined at the source code. We should define some identical states that can be used for the input of the neural network if the game have it. Later, it can be used to increment the input of the neural network. Also, in the paper, the identical state will be used to evaluate the the state in the leaf node of the MCTS, where it will be uniformly selected at random. The identical states usually is a dihedral reflection or rotation of the original state. I think, the purpose of this component is to make the training faster and make sure to include the state that should have the same situation or evaluation. Unfortunately, this game doesn’t have the identical states. So we cannot use this component for this game. We will use Reward Function to tell the final outcome whether the agent is win or lose. Since we use Monte Carlo Tree Search, we will call the Reward Function at the terminal state. Then it will become the output of the neural network that we want to optimize. The reward function is the utility function that we defined at part 2. We will normalize the value to the range to {-1,1}. Here’s the high-level pseudocode implementation: def reward_function(state, player): if state.win(player): return 1 else return -1 Since the reward is only called when the state is in terminal state, this is called sparse reward. The neural network will be trained to evaluate and predict the reward when the state is not terminal. For the implementation, you can see the State.sparse_eval() function. how the terminal state is called is defined in the Part 1. github.com In this section, we will create the architecture of the neural network used in the AlphaZero. In the paper, they use 20 residual blocks followed by policy head and value head. They used it because it’s the state-of-the-art deep learning architecture at that time in the Computer Vision tasks. Of course, we won’t use that. Especially for me who have a low-budget and minimum resource for doing this experiment 😢. Instead, we will use a simplified architecture. We use the architecture defined in the [Source 2] with several changes. Here’s the architecture: So, we will have 4 residual blocks with 2 CNNs followed by a policy head and and value head. The hyperparameter is also simplified. The output units of each layer is reduced according to my GPU. I think that the hyperparameter used in that article is enough. So, We will follow the hyperparameter used in that article with little changes (such as increase or decrease the output units by a little). The input of the neural network is the state representation that we have defined above. There are two outputs of the neural network, a scalar features v and vector of move probabilities p. The range of the output of neural network is {-1,1} for the v and {0,1} for the p. This is why we use tanh for the activation function for the v and softmax for the activation function for the p. The neural network will minimize the following objective function: Where vθ(st) is the output of value head, a scalar one, which evaluate the situation of the current state and pθ(st), the output of policy head, is the predicted policy from state st. vθ(st) will be trained to be as close as zt, which is the final outcome of the game for a player in respect to the perspective of the chosen Point of View (POV). in our case, the POV is the white player. zt value can be -1, 0, or 1 depending on the outcome of the game. vθ(st) will be trained to calculate the evaluation of the current state. The πt is the estimate of the policy from state st. We also need to train the parameter of the neural network so that pθ(st) is close enough with the πt. pθ(st) will be a vector of probability distribution which tell us that the higher the value, the good the action is and has a high chance to be chosen. It will be trained to be as close as πt. How to get πt is defined in the next section. Of course, it also needs to be same perspective of the chosen POV. The optimizer is using Adam Optimizer with the defined learning rate. So, in summary, we will minimize the error on predicting the evaluation of the current state and the policy of the current state. Let the batch_size is the total instance to be input of our Neural Network, The input shape is (batch_size, 9,9,140) for the state representation. There are two outputs, the policy head and value head. Policy head has (batch_size, 2998) (the total of unique actions) and value head has (batch_size, 1) shape. Later, the neural network model is used in the Monte Carlo Tree Search simulation for evaluating and predicting the policy (policy evaluation) of the state. The model will be optimized to minimize the loss at the end on every episodes. For the implementation, see below (class PawnNetZero): github.com Before we dive into the Monte Carlo Tree Search, I suggest to read a brief description about MCTS here. We will use the Monte Carlo Tree Search to improve the policy estimation quality (policy improvement). This will be the component to predict the action of an agent given a state. The MCTS is used for simulating the game, which is self-learning (The agent plays as two players that alternately takes the turn). For every step at each episodes ( one full game), the MCTS is simulated until the given number of simulation. It’s also a search algorithm like minimax that we previously used, but the MCTS won’t expand all possible action and use guided ‘heuristic’ instead to determine which node to be expanded. The tree in MCTS will consists of nodes that represent a board configuration. A directed edge exists between each nodes represents the valid action of a state. The edge is different from Minimax Tree Search,not only to save the action name, the edge has several parameters that will be updated each simulations. The edge will contains several parameter that we will be updated: Q(s,a) : The expected reward or mean reward for taking action a on state s, it will be updated in the backup step. This will be the average of the evaluation or reward for all predicted vθ(st)which is produced by the neural network or the actual reward (-1,0,1) in terminal state in the leaf node (which is the descendant of the node s).N(s,a) : The number of times the simulation take action a in state sP(s,a) : The estimate probability of taking action a in state s that is policy produced by the model of the neural network. Q(s,a) : The expected reward or mean reward for taking action a on state s, it will be updated in the backup step. This will be the average of the evaluation or reward for all predicted vθ(st)which is produced by the neural network or the actual reward (-1,0,1) in terminal state in the leaf node (which is the descendant of the node s). N(s,a) : The number of times the simulation take action a in state s P(s,a) : The estimate probability of taking action a in state s that is policy produced by the model of the neural network. Whereas the node will contain several parameter: N(s) : The number of times the simulation take this state (s). It’s equal to the sum of N(s,a) for every possible action a in the state s. N(s) : The number of times the simulation take this state (s). It’s equal to the sum of N(s,a) for every possible action a in the state s. At the start of each episodes, the MCTS is initialized with a single root node. The root node is also act as a leaf node when it is initialized. From this root, the MCTS will expand the tree until the limit number of simulation is reached. After we initialize the tree, there are 4 steps on doing the MCTS in AlphaZero: SelectExpand and EvaluateBackupPlay Select Expand and Evaluate Backup Play The step 1–3 is iterated by the number of simulations and then do the step 4. The simulation in the MCTS will begin at the root node (s0), and finishes if the simulation encounter the leaf node sL at time step L. At each of these time steps, for every node that is already expanded in the Expand and Evaluate step, an action is selected according to the parameter in the edge of each node. Here we will select the action a in the state s which has the highest U(s,a), the Upper Confidence Bound using variant of the PUCT algorithm. where cpuct is a hyperparameter to determine the level of exploration. sum of N(s,b) is equal to N(s). If s is s0 (root node), P(s,a) is changed to be P (s, a) = (1 — u000fe)*pa + u000fe*ηa where η is probability distribution by using Dirichlet noise with the chosen parameter and e is 0.25 . This will make the exploration to try all the moves in the root state. This step will be done until the leaf node is found. If leaf node is found, the Expand and Evaluate step is called. If the current node is the leaf node, this action will be performed. We will evaluate the state sL with the representation that we have defined above to be the input of the neural network. It will output the policy and the value of evaluation of the current state. The input will be transformed into any identical state at random in uniform probability distribution (It can choose the unchanged one). Because we don’t have it in this game, the state won’t be transformed and the input of neural network will always be the same. so in the implemention of EvoPawness (Temporary Name), the output of function di will return the sL without transforming the form. The output is the policy p and the value v for the state sL explained in the previous section. If p is the action of the transformed state, the action should be transformed back to be the method of the original state. in p, the invalid action probability will be masked and the valid action will be normalized, so that the vector will sum to one. Then, the Leaf node is expanded with edge containing all possible action in that state. Each edge and the leaf node parameter is initialized to : N(sL,a) = 0, Q(sL,a) = 0, N(s) = 0, P = p, P(sL,a) = paWhere a is a possible action in the state sL. After we expand the leaf node (sL), the parameter will be updated in a backward pass to all of the parent’s node until root node, which is through each step t ≤ L. These parameters will be updated as follow: Q(st,at) = (Q(st,at)* N(st,at) + v)/ (N(st,at) + 1)N(st,at) = N(st,at) + 1N(st) = N(st) + 1 Note that v = v * -1 if st 's player is different than sL. for example: st’s turn is black and sL’s turn is white. Since this is a zero sum game, the evaluation of opposite player (v) will be the negative of the current player. After do Backup steps, do the Select step from the root node again if the maximum of number of simulation hasn’t been reached. These steps will be iterated until maximum of number of simulation is reached. If it has been reached, do this step: At the end of the search, it is time to select the action a in the root position s0 based on the parameter updated at simulations. Probability of action a given root state (πa|s) is selected proportional to the exponentiated visit count N(s,a) counted at the simulation. We will calculate the policy of all the action with the following formula: Where τ is a temperature that is used to control the degree of exploration. When the turn or step in the game is lower than 30, the τ is set to 1, infinitesimal otherwise. The high-level pseudocode implementation of the MCTS is as follow: The implementation can be found here: github.com Note that the implementation in the repository will be different but it has the same objective. In the repository, I include select, expand, and evaluate step in the ‘expand()’ function. For maintaining the quality of the model, we must ensure that the model that is used is the best one. To do that, AlphaZero will compare the quality of the the current best model and the current model. It’s quite easy to do it. We need two agents that will fight each other. These models are pitted each other for n round by the chosen max simulation and limited by max_step to prevent the game from infinite loop that will make the terminal state unreachable. This will return the score which will determine the best model. n can be fill by any number. If the current model wins by a chosen margin (in the paper 55%), the best model is replaced by the current model. The best model is used for the next episode. If the best model wins, the best model remains to be used for the next episode. We will initiate 2 MCTS, one with the best model neural network and the other with current neural network. The color of the player can be decided by yourself (for example : white is best model and black is current model). Here’s the pseudo code The implementation can be found here (fight_agent() function): github.com That’s it. We have defined all the components ready for the AlphaZero. Now we will connect all of our defined components and do the AlphaZero algorithm. After we define all the component that will be used for the MCTS, let’s wrap it up. The step of implementing AlphaZero based on the components that we have defined is as follow: Generate all unique actions that can be used for every players.Create the neural network model which will be used to evaluate in the MCTS with the input of the unique generated actions. The policy head in the model will adjust its output shape by the total of unique actions.Create structure data deque which will be used to keep the information about the result of every self-play and will be used to be input of the neural network. The maximum length of the deque must be defined.For every episodes, we create new instances of MCTS which will be used to train our agent by self-playing by itself. We will see this steps more detail below.After the self-play is done, train the neural network model based on the data generated from self play in the deque. The total of instances in the deque is limited to the defined maximum length of deque.After we train the model, we will check whether the current model is better than current best model. If it’s true, then change the best model into current model. The best model will be used for evaluating for the next episode. Generate all unique actions that can be used for every players. Create the neural network model which will be used to evaluate in the MCTS with the input of the unique generated actions. The policy head in the model will adjust its output shape by the total of unique actions. Create structure data deque which will be used to keep the information about the result of every self-play and will be used to be input of the neural network. The maximum length of the deque must be defined. For every episodes, we create new instances of MCTS which will be used to train our agent by self-playing by itself. We will see this steps more detail below. After the self-play is done, train the neural network model based on the data generated from self play in the deque. The total of instances in the deque is limited to the defined maximum length of deque. After we train the model, we will check whether the current model is better than current best model. If it’s true, then change the best model into current model. The best model will be used for evaluating for the next episode. When the step is doing the self-play, we will do the steps as below: First, we need to initiate the state of the game and the MCTS. Then, do the following: First, we fill the parameter inside the MCTS (self_play()), then we get the action probability on the root (play()). We fill the deque with the action, the state, and the player information. After the state reached the terminal or the max step, we finally add the reward information to the deque. After we fill the reward on the deque, we will append the content of the deque to the global deque which will be used to train the neural network. The self_play function is a MCTS simulator which acts this way: That’s it, so every simulation of MCTS will simulate until leaf node is found. If it has been found, then do the expand and evaluate. If not, do the selection. That’s it, we have defined the how to create the AlphaZero implementation to the game. For the implementation, you can see the fit_train() and on the train_module.py in the repository. github.com To run the training, use main_from_start.py for training from the start. and main_from_continue.py to train from the checkpoint. For now, I suggest that you don’t try to train the model until I’ve refactored and clean the code. I plan to do it on next Saturday. Below is the code of main_from_start.py github.com There are several lesson that I learnt on implementing the AlphaZero. I’ve run the code to train the model. I’ve learnt that at first, It is very hard to gain an episode which results to win or lose. It often end in draw (max steps reached). I conclude that the max simulation that I set is not enough. I need higher max simulation on the MCTS. I’ve also tried another way to solve it. I tried to hack the simulation of MCTS by letting the agent always attack the enemy. If you are confused what is greed variable inside the MCTS, for 1/8 of maximum episodes that I set and the chosen minimum step, the simulation will always make the attack action and promote action has bigger Q on the Upper Confidence Bound than other actions. This will be disabled when pitting two models. I need to find a better way to solve this problem.I need to implement multi-thread on simulating the MCTS. A single thread still can be used, but it’s very slow. So, in the next part, I will try to implement multi-thread MCTS.I haven’t tuned the hyperparameter of the neural network and MCTS. So, I still don’t know how many residual layers should I use. Currently, I use 4 residual layers. I didn’t tune it because the training is very slow 😢.Make sure to read the paper thoroughly. I’ve fixed my code several times because I skipped some part on the paper. I’ve run the code to train the model. I’ve learnt that at first, It is very hard to gain an episode which results to win or lose. It often end in draw (max steps reached). I conclude that the max simulation that I set is not enough. I need higher max simulation on the MCTS. I’ve also tried another way to solve it. I tried to hack the simulation of MCTS by letting the agent always attack the enemy. If you are confused what is greed variable inside the MCTS, for 1/8 of maximum episodes that I set and the chosen minimum step, the simulation will always make the attack action and promote action has bigger Q on the Upper Confidence Bound than other actions. This will be disabled when pitting two models. I need to find a better way to solve this problem. I need to implement multi-thread on simulating the MCTS. A single thread still can be used, but it’s very slow. So, in the next part, I will try to implement multi-thread MCTS. I haven’t tuned the hyperparameter of the neural network and MCTS. So, I still don’t know how many residual layers should I use. Currently, I use 4 residual layers. I didn’t tune it because the training is very slow 😢. Make sure to read the paper thoroughly. I’ve fixed my code several times because I skipped some part on the paper. In this article, we have constructed all the components that will be used to implement the AlphaZero. We also have implemented the AlphaZero algorithm. This article haven’t told the result of the AlphaZero yet since the training is not done yet. This article still use a single GPU on training the model. It also uses a single thread to run the simulation of MCTS. So, the training will be very slow. Woah, look at my 25 minutes read time article 😆. Finally the article is done and published. Thanks to the several articles that I’ve read, I can experiment the AlphaZero algorithm and understand the algorithm. Since the training is not done yet, I plan to create the next part that will focus on the improvement and the result of implementing AlphaZero to this game. Unfortunately, with the limited resource that I have, I’m afraid that this project will be on hold until I get a new computer to experiment it. Well, you see, I’m unemployed (for several reasons) so I have limited money here 😢. I will try to fix the mess of the code and make it to be executed easily next week. Currently, the code is very messy and has high verbosity when the program is run. I welcome any feedback that can improve myself and this article. I’m in the process of learning on writing and reinforcement learning. I really need a feedback to become better. Just make sure to give feedback in a proper manner 😄. Oh, I promised to tell you the details of the project structure and the GUI at the last part. Sorry, I forgot to write it 😅. If I have the time, I will write it on my next article. For my several next projects, I will focus on NLP or Computer Vision tasks. I will write something about using GAN on these tasks. I want to learn GAN and implement it, since it’s a hot topic in the Deep Learning at the moment. If you want another article from me like this one, please clap this article 👏 👏. It will boost my spirit to write my next article. I promise to make a better article about AI . See ya in my next article! Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1 Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2 Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3 web.stanford.edu medium.com [Source 2] by David Foster [Source 3] Silver, David, et al. “Mastering the game of Go without human knowledge.” Nature 550.7676 (2017): 354. [Source 4] Silver, David, et al. “Mastering chess and shogi by self-play with a general reinforcement learning algorithm.” arXiv preprint arXiv:1712.01815 (2017). Thanks Thomas Simonini for suggesting me to move on implementing the Deep Q Network to Policy Based Learning.
[ { "code": null, "e": 607, "s": 172, "text": "Hello everyone, welcome to the part 3 of making AI on the EvoPawness (Temporary Name). In this article, we will implement AlphaZero Algorithm to the game. This article will tell you a short summary of the AlphaZero and the implementation of the AlphaZero, albeit the simplified one. We will do it in a step by step. We will use some of terminology stated in the Part 1 such as Result Function, Possible Actions, and Terminal Function." }, { "code": null, "e": 939, "s": 607, "text": "The experiment is not done yet. It takes a long time to train the agent for this game, especially with a single computer. I’ve trained the agent for a day. Unfortunately, the agent is still not good enough. Even so, It has learnt a few strategy such as attacking the king continuously with knight if the knight can attack the king." }, { "code": null, "e": 1214, "s": 939, "text": "I stopped training the agent to let my computer rest. I’m afraid my laptop will be broken if I force it to train more than a day. I also limited the hyperparameter of the AlphaZero to speed up the training time. I’m sorry for my limited resources on doing this experiment 😿." }, { "code": null, "e": 1483, "s": 1214, "text": "Even though the experiment is not complete, I will try to write how I implement the AlphaZero on this game. I hope that it will give an enlightenment to someone who want to learn about a reinforcement learning algorithm, AlphaZero, and implementing them to their game." }, { "code": null, "e": 1567, "s": 1483, "text": "I’ve made several changes on the game’s rule. The game still remains deterministic." }, { "code": null, "e": 1822, "s": 1567, "text": "This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article. I hope that my writing skill will increase by publishing this article and the content benefits you 😄." }, { "code": null, "e": 1890, "s": 1822, "text": "Brace yourself, It will be a long article. It has 25 minutes read !" }, { "code": null, "e": 2035, "s": 1890, "text": "RepositoryBrief description about AlphaZeroChanged RuleStepsComponents of AlphaZeroImplementation of AlphaZeroLesson LearnedConclusionAfterwords" }, { "code": null, "e": 2046, "s": 2035, "text": "Repository" }, { "code": null, "e": 2080, "s": 2046, "text": "Brief description about AlphaZero" }, { "code": null, "e": 2093, "s": 2080, "text": "Changed Rule" }, { "code": null, "e": 2099, "s": 2093, "text": "Steps" }, { "code": null, "e": 2123, "s": 2099, "text": "Components of AlphaZero" }, { "code": null, "e": 2151, "s": 2123, "text": "Implementation of AlphaZero" }, { "code": null, "e": 2166, "s": 2151, "text": "Lesson Learned" }, { "code": null, "e": 2177, "s": 2166, "text": "Conclusion" }, { "code": null, "e": 2188, "s": 2177, "text": "Afterwords" }, { "code": null, "e": 2282, "s": 2188, "text": "In case you start reading the progress of the game with this article, here is the repository:" }, { "code": null, "e": 2293, "s": 2282, "text": "github.com" }, { "code": null, "e": 2339, "s": 2293, "text": "I’ve added several changes to the repository:" }, { "code": null, "e": 2368, "s": 2339, "text": "Add AlphaZero Implementation" }, { "code": null, "e": 2404, "s": 2368, "text": "Reformat module or folder structure" }, { "code": null, "e": 2438, "s": 2404, "text": "Change action representation key." }, { "code": null, "e": 2497, "s": 2438, "text": "Change the game model and controller to match the new rule" }, { "code": null, "e": 2740, "s": 2497, "text": "Note : For now, I suggest that you do not try to train the model until I refactor and clean the code. And also, the code is still super messy, I will try to clean and refactor it as soon as possible. In the next Saturday, I will try to do it." }, { "code": null, "e": 2947, "s": 2740, "text": "Edit (3/12/2018) : I have cleaned the code. Now we have Config.py to edit the configuration. See main.py -h on how to launch the program. For further information, wait for me to edit the README.md tomorrow." }, { "code": null, "e": 3003, "s": 2947, "text": "Edit 2 (10/12/2018) : I’ve pushed the updated README.md" }, { "code": null, "e": 3338, "s": 3003, "text": "AlphaZero is created by Deep Mind which is published in the following paper [Source 4]. What makes it special is that it can beat the best AI of chess and shogi under 24 hours training. It makes this algorithm is the best at that time on AI game. For further information you can see this article on how powerful this algorithm can be." }, { "code": null, "e": 3528, "s": 3338, "text": "It also don’t have human expertise as the input (except the rule of the game). It learns from zero to become the best AI game program which beat the best AI for the board game at that time." }, { "code": null, "e": 3885, "s": 3528, "text": "I also find that the algorithm is very simple yet astonishing. The algorithm will explore the possible paths that is promising with the current knowledge. The searched path will tell whether the current path is favourable or not. The score of how favourable it is is backed down and be used to be a consideration whether this path should be explored again." }, { "code": null, "e": 4056, "s": 3885, "text": "After the exploration on thinking the future possibility, take the action that is explored the most. It means that this action can be good if this path is often explored." }, { "code": null, "e": 4333, "s": 4056, "text": "At the end of the game, evaluate whether the path that it choose match to the outcome of the game. It tells us whether the knowledge misjudged the path that is chosen when exploring the possible future paths. The knowledge will be updated according to the outcome of the game." }, { "code": null, "e": 4533, "s": 4333, "text": "The AlphaZero need the game with perfect information (the game state is fully known to both players) and deterministic. Since this game has both of them, AlphaZero algorithm can be used to this game." }, { "code": null, "e": 5138, "s": 4533, "text": "In this article, we will simplify the architecture used on the paper. We will use a simplified AlphaZero implementation based on the article that I’ve read. In the implementation used by David Foster [Source 2], he uses 4 residual layers that is connected to a policy head and a value head. I used his architecture and change some hyperparameters. I also see the implementation of the AlphaZero in the [Source 1] and modify the implementation to suit this game. I follow the Monte Carlo Tree Search implementation in that article and change the implementation from using recursive to structure data tree." }, { "code": null, "e": 5575, "s": 5138, "text": "The implementation used on these articles are inline with the paper with some skipped parts. There are several steps that I skipped such as v resignation. In these two articles, they do not implement the stacked state. In this article, I implement the stacked state and using 140 planes as the input of the model. In this article, the implementation of the AlphaZero also haven’t implemented multi-thread MCTS by using virtual loss yet." }, { "code": null, "e": 6050, "s": 5575, "text": "The rune will spawn on 3 different positions. There are (on y, x axis) (4,0) , (4,4), and (4,8). The rune that spawn at (4,0) will raise 2 attack points. The rune that spawn at (4,4) will raise 2 health points. and the rune that spawn at (4,8) will raise 1 step points.Rune position that is occupied by a pawn when the time of rune spawn (every 5 turns) will not spawn the rune.Step, health, and attack points has a limit. 3 for steps, 20 for health, and 8 for attack points" }, { "code": null, "e": 6320, "s": 6050, "text": "The rune will spawn on 3 different positions. There are (on y, x axis) (4,0) , (4,4), and (4,8). The rune that spawn at (4,0) will raise 2 attack points. The rune that spawn at (4,4) will raise 2 health points. and the rune that spawn at (4,8) will raise 1 step points." }, { "code": null, "e": 6430, "s": 6320, "text": "Rune position that is occupied by a pawn when the time of rune spawn (every 5 turns) will not spawn the rune." }, { "code": null, "e": 6527, "s": 6430, "text": "Step, health, and attack points has a limit. 3 for steps, 20 for health, and 8 for attack points" }, { "code": null, "e": 6593, "s": 6527, "text": "This article will implement the AlphaZero in the following order:" }, { "code": null, "e": 7120, "s": 6593, "text": "Define the state representation for the input of the model. We use stacked state.Define the action representation for the game.Decide which side will be used to represent the state (black or white) for all players and define how to change the side.Define some identical states that can be used to increment the input of the modelDefine reward functionImplement the architecture of the neural network that is used to output the policy evaluationImplement the Monte Carlo Tree SearchAdd duel function to evaluate the best model." }, { "code": null, "e": 7202, "s": 7120, "text": "Define the state representation for the input of the model. We use stacked state." }, { "code": null, "e": 7249, "s": 7202, "text": "Define the action representation for the game." }, { "code": null, "e": 7371, "s": 7249, "text": "Decide which side will be used to represent the state (black or white) for all players and define how to change the side." }, { "code": null, "e": 7453, "s": 7371, "text": "Define some identical states that can be used to increment the input of the model" }, { "code": null, "e": 7476, "s": 7453, "text": "Define reward function" }, { "code": null, "e": 7570, "s": 7476, "text": "Implement the architecture of the neural network that is used to output the policy evaluation" }, { "code": null, "e": 7608, "s": 7570, "text": "Implement the Monte Carlo Tree Search" }, { "code": null, "e": 7654, "s": 7608, "text": "Add duel function to evaluate the best model." }, { "code": null, "e": 7774, "s": 7654, "text": "Before we go to this part, I suggest that if you haven’t read the part 1, read it. It will cover the rules of the game." }, { "code": null, "e": 8245, "s": 7774, "text": "We will see the representation state for the input of the neural network in this section. The input of the neural network is an image stack that represents the state. There are 28 input features used in the implementation. Here, we will use 5-step history (Note : in the paper of AlphaZero, the number of step history is 8. Here, this article will try a different number). From the number of step-history that we use, it means that there are 140 input features (28 X 5)." }, { "code": null, "e": 8473, "s": 8245, "text": "The history will save the state representation at the previous turn. If we use 5-step history, given the state is at T turn, we will take T, T-1, T-2, T-3, T-4 state that will be stacked and become input for the neural network." }, { "code": null, "e": 8502, "s": 8473, "text": "Here are the input features:" }, { "code": null, "e": 8577, "s": 8502, "text": "No 4–10, 13 use binary features whereas the others use frequency features." }, { "code": null, "e": 8799, "s": 8577, "text": "Since, the board is 9 x 9, if we have batch_size as the total instance of the input of neural network, we have (batch_size, 9, 9, 140) shape as the input of the neural network. So, we have 4 dimensional data as the input." }, { "code": null, "e": 8891, "s": 8799, "text": "For the code, you can see the get_representation_stack() function in the source code below:" }, { "code": null, "e": 8902, "s": 8891, "text": "github.com" }, { "code": null, "e": 9058, "s": 8902, "text": "In the source code, we will use AIElements class which contains the elements that we define in the part 1. We use deque as our data structure (like stack)." }, { "code": null, "e": 9381, "s": 9058, "text": "Before we get the input representation of the neural network, we will stack the state, the state representation that we defined at Part 1, into a deque data structure with the desired max length (in this article, we set it to 5). Then we process the deque and change it into an input representation for the neural network." }, { "code": null, "e": 9493, "s": 9381, "text": "There are 5 type of actions that is available in the game. There are Activate, Promote, Move, Attack, and Skip." }, { "code": null, "e": 9666, "s": 9493, "text": "For the activate action, we need to select the pawn that want to be activated. We need the coordinates of the pawn. So we have 81 (9 x 9) different unique activate actions." }, { "code": null, "e": 9788, "s": 9666, "text": "Note: we have a different action key representation that is stated in the Part 1, the new representation is stated below:" }, { "code": null, "e": 9892, "s": 9788, "text": "Action Key Representation for the activate action: a*y,xy : pawn's axis-yx : pawn's axis-xexample a*1,0" }, { "code": null, "e": 10259, "s": 9892, "text": "For the Promote action, we need to select the pawn that want to be promoted then select the possible choice to promote the pawn. We need the coordinates of the pawn . We have 9 x 9 different unique actions for selecting the possible pawn. There are 4 promoted pawn type (Queen, Rook, Bishop, Knight), so there are 324 (9 x 9 x 4) unique way to do the promote action." }, { "code": null, "e": 10452, "s": 10259, "text": "Action key representation for the promote action : p*y,x*choicey : pawn's axis-yx : pawn's axis-xchoice : promote choice, K for Knight, R for Rook, B for Bishop, and Q for Queenexample p*3,3*Q" }, { "code": null, "e": 11108, "s": 10452, "text": "For the attack and move action, In this game, we have 7 type of pawns. The direction of the move has been defined in the Part 1. In the part 1, we have attack and move as separate action. In this article, we will combine the attack action and the move action into one (they don’t overlap, so we can combine them). We can see that the direction of move of Soldier, Rook, Bishop, and King is a subset of the Queen. It moves vertical, horizontal, and diagonally in the N, NE, E, SE, W, SW, W, and NW direction. Only knight has different moves. It moves in L-shape in all points direction of the compass. In summary, we have 2 type of moves, Queen and Knight." }, { "code": null, "e": 11653, "s": 11108, "text": "We have 2 steps on doing the action: selecting the pawn and selecting the legal move for the pawn based on the possible action. In this case, we have 81 (9 x 9) different actions for selecting the pawn. Then for selecting the legal move, we have 8 different actions for knight move’s type and 24 (8 x 3) for queen move’s type (Note : we have 3 as the limit of step points, so the queen move can consists of 24 type of move). The total of unique actions that can be made is 2592 (81 x 32) for selecting the legal move for attack and move action." }, { "code": null, "e": 11918, "s": 11653, "text": "Action Key Representation for the activate action: m*y1,x1*y2,x2y1 : selecting the pawn in axis-yx1 : selecting the pawn in axis-xy2 : direction of the move in axis-yx2 : direction of the move in axis-xExample m*0,1*2,1 (means that it will move from (0,1) to (2,2)" }, { "code": null, "e": 11957, "s": 11918, "text": "Skip if the player cannot do anything." }, { "code": null, "e": 12004, "s": 11957, "text": "The action key representation for skip is skip" }, { "code": null, "e": 12060, "s": 12004, "text": "The total of the unique action is 2998 (9 x 9 x 37 + 1)" }, { "code": null, "e": 12390, "s": 12060, "text": "The action representation is used to encode the probability distribution that is used for selecting the action later on doing the Monte Carlo Tree Search (MCTS). Later, the action that is not possible to do in the state is masked and set the probability to 0 and re-normalize the probability distribution for the possible action." }, { "code": null, "e": 12586, "s": 12390, "text": "See the repository for the implementation on how to generate all possible action. I used LabelEncoder and OneHotEncoder provided in scikit-learn library to encode the action into One Hot Encoder." }, { "code": null, "e": 12621, "s": 12586, "text": "One Hot Encoder Class (see fit()):" }, { "code": null, "e": 12632, "s": 12621, "text": "github.com" }, { "code": null, "e": 12692, "s": 12632, "text": "Generate all unique actions (see action_spaces() function):" }, { "code": null, "e": 12703, "s": 12692, "text": "github.com" }, { "code": null, "e": 13145, "s": 12703, "text": "In the paper of AlphaZero, we need to orientate the perspective of the board to the current player. We must decide which side will be the perspective for both players. I choose white as the perspective or Point of View (POV) for both players. So if the current turn is black player, we will make the black player perspective become the white player perspective. If the current turn is white player, we will not change the player perspective." }, { "code": null, "e": 13165, "s": 13145, "text": "How can we do this?" }, { "code": null, "e": 13404, "s": 13165, "text": "If this is a chess game, it will be easy. Just invert the color of the pieces. In this game, we cannot do that. The king is fixed at that position and cannot move. So, inverting the pieces will make the state invalid. So how can we do it?" }, { "code": null, "e": 13508, "s": 13404, "text": "We need to mirror or reflect the position of each pawns. After that, invert the color of all the pawns." }, { "code": null, "e": 13531, "s": 13508, "text": "Here’s the pseudocode:" }, { "code": null, "e": 13768, "s": 13531, "text": "def mirror(self, pawn): pawn.y = pawn.y - 4 # 4 is the center position of the board pawn.y *= -1 # after we move the center to 0, we mirror it pawn.y += 4 # Then we move the center point to 4 pawn.color = inverse(pawn.color)" }, { "code": null, "e": 13860, "s": 13768, "text": "We do that to all of the pawns (King included). We have mirrored the position of the pawns." }, { "code": null, "e": 14281, "s": 13860, "text": "As we change the perspective of the board by changing the pawn’s position, we need to change the action too. We need to mirror the coordinates of the action and the direction if the action is move or attack. It’s similar to change the position of the pawn, we will change the coordinates of the action by mirroring the coordinates by manipulating the y-axis. For the direction, we only need to multiply the y-axis by -1." }, { "code": null, "e": 14294, "s": 14281, "text": "For example:" }, { "code": null, "e": 14454, "s": 14294, "text": "{} = * means multiplication in this bracketoriginal = a*2,3mirror = a*{(2-4)*-1+4},3 = a*6,3original = m*1,0*1,0mirror = m*{(1-4)*-1+4,0}*{1*-1},0 = m*7,0*-1,0" }, { "code": null, "e": 14509, "s": 14454, "text": "That’s it how we change the perspective of the player." }, { "code": null, "e": 14587, "s": 14509, "text": "For the implementation, see all of the functions defined in this source code:" }, { "code": null, "e": 14598, "s": 14587, "text": "github.com" }, { "code": null, "e": 14778, "s": 14598, "text": "It’s essentially the same as the pseudocode, but in OOP way. We will change the attributes of all the object of pawns. The mirror of the action is also defined at the source code." }, { "code": null, "e": 15360, "s": 14778, "text": "We should define some identical states that can be used for the input of the neural network if the game have it. Later, it can be used to increment the input of the neural network. Also, in the paper, the identical state will be used to evaluate the the state in the leaf node of the MCTS, where it will be uniformly selected at random. The identical states usually is a dihedral reflection or rotation of the original state. I think, the purpose of this component is to make the training faster and make sure to include the state that should have the same situation or evaluation." }, { "code": null, "e": 15467, "s": 15360, "text": "Unfortunately, this game doesn’t have the identical states. So we cannot use this component for this game." }, { "code": null, "e": 15728, "s": 15467, "text": "We will use Reward Function to tell the final outcome whether the agent is win or lose. Since we use Monte Carlo Tree Search, we will call the Reward Function at the terminal state. Then it will become the output of the neural network that we want to optimize." }, { "code": null, "e": 15900, "s": 15728, "text": "The reward function is the utility function that we defined at part 2. We will normalize the value to the range to {-1,1}. Here’s the high-level pseudocode implementation:" }, { "code": null, "e": 15998, "s": 15900, "text": "def reward_function(state, player): if state.win(player): return 1 else return -1" }, { "code": null, "e": 16199, "s": 15998, "text": "Since the reward is only called when the state is in terminal state, this is called sparse reward. The neural network will be trained to evaluate and predict the reward when the state is not terminal." }, { "code": null, "e": 16328, "s": 16199, "text": "For the implementation, you can see the State.sparse_eval() function. how the terminal state is called is defined in the Part 1." }, { "code": null, "e": 16339, "s": 16328, "text": "github.com" }, { "code": null, "e": 16752, "s": 16339, "text": "In this section, we will create the architecture of the neural network used in the AlphaZero. In the paper, they use 20 residual blocks followed by policy head and value head. They used it because it’s the state-of-the-art deep learning architecture at that time in the Computer Vision tasks. Of course, we won’t use that. Especially for me who have a low-budget and minimum resource for doing this experiment 😢." }, { "code": null, "e": 16897, "s": 16752, "text": "Instead, we will use a simplified architecture. We use the architecture defined in the [Source 2] with several changes. Here’s the architecture:" }, { "code": null, "e": 16990, "s": 16897, "text": "So, we will have 4 residual blocks with 2 CNNs followed by a policy head and and value head." }, { "code": null, "e": 17296, "s": 16990, "text": "The hyperparameter is also simplified. The output units of each layer is reduced according to my GPU. I think that the hyperparameter used in that article is enough. So, We will follow the hyperparameter used in that article with little changes (such as increase or decrease the output units by a little)." }, { "code": null, "e": 17384, "s": 17296, "text": "The input of the neural network is the state representation that we have defined above." }, { "code": null, "e": 17681, "s": 17384, "text": "There are two outputs of the neural network, a scalar features v and vector of move probabilities p. The range of the output of neural network is {-1,1} for the v and {0,1} for the p. This is why we use tanh for the activation function for the v and softmax for the activation function for the p." }, { "code": null, "e": 17748, "s": 17681, "text": "The neural network will minimize the following objective function:" }, { "code": null, "e": 17932, "s": 17748, "text": "Where vθ(st) is the output of value head, a scalar one, which evaluate the situation of the current state and pθ(st), the output of policy head, is the predicted policy from state st." }, { "code": null, "e": 18275, "s": 17932, "text": "vθ(st) will be trained to be as close as zt, which is the final outcome of the game for a player in respect to the perspective of the chosen Point of View (POV). in our case, the POV is the white player. zt value can be -1, 0, or 1 depending on the outcome of the game. vθ(st) will be trained to calculate the evaluation of the current state." }, { "code": null, "e": 18735, "s": 18275, "text": "The πt is the estimate of the policy from state st. We also need to train the parameter of the neural network so that pθ(st) is close enough with the πt. pθ(st) will be a vector of probability distribution which tell us that the higher the value, the good the action is and has a high chance to be chosen. It will be trained to be as close as πt. How to get πt is defined in the next section. Of course, it also needs to be same perspective of the chosen POV." }, { "code": null, "e": 18805, "s": 18735, "text": "The optimizer is using Adam Optimizer with the defined learning rate." }, { "code": null, "e": 19244, "s": 18805, "text": "So, in summary, we will minimize the error on predicting the evaluation of the current state and the policy of the current state. Let the batch_size is the total instance to be input of our Neural Network, The input shape is (batch_size, 9,9,140) for the state representation. There are two outputs, the policy head and value head. Policy head has (batch_size, 2998) (the total of unique actions) and value head has (batch_size, 1) shape." }, { "code": null, "e": 19480, "s": 19244, "text": "Later, the neural network model is used in the Monte Carlo Tree Search simulation for evaluating and predicting the policy (policy evaluation) of the state. The model will be optimized to minimize the loss at the end on every episodes." }, { "code": null, "e": 19535, "s": 19480, "text": "For the implementation, see below (class PawnNetZero):" }, { "code": null, "e": 19546, "s": 19535, "text": "github.com" }, { "code": null, "e": 19650, "s": 19546, "text": "Before we dive into the Monte Carlo Tree Search, I suggest to read a brief description about MCTS here." }, { "code": null, "e": 20258, "s": 19650, "text": "We will use the Monte Carlo Tree Search to improve the policy estimation quality (policy improvement). This will be the component to predict the action of an agent given a state. The MCTS is used for simulating the game, which is self-learning (The agent plays as two players that alternately takes the turn). For every step at each episodes ( one full game), the MCTS is simulated until the given number of simulation. It’s also a search algorithm like minimax that we previously used, but the MCTS won’t expand all possible action and use guided ‘heuristic’ instead to determine which node to be expanded." }, { "code": null, "e": 20570, "s": 20258, "text": "The tree in MCTS will consists of nodes that represent a board configuration. A directed edge exists between each nodes represents the valid action of a state. The edge is different from Minimax Tree Search,not only to save the action name, the edge has several parameters that will be updated each simulations." }, { "code": null, "e": 20636, "s": 20570, "text": "The edge will contains several parameter that we will be updated:" }, { "code": null, "e": 21165, "s": 20636, "text": "Q(s,a) : The expected reward or mean reward for taking action a on state s, it will be updated in the backup step. This will be the average of the evaluation or reward for all predicted vθ(st)which is produced by the neural network or the actual reward (-1,0,1) in terminal state in the leaf node (which is the descendant of the node s).N(s,a) : The number of times the simulation take action a in state sP(s,a) : The estimate probability of taking action a in state s that is policy produced by the model of the neural network." }, { "code": null, "e": 21503, "s": 21165, "text": "Q(s,a) : The expected reward or mean reward for taking action a on state s, it will be updated in the backup step. This will be the average of the evaluation or reward for all predicted vθ(st)which is produced by the neural network or the actual reward (-1,0,1) in terminal state in the leaf node (which is the descendant of the node s)." }, { "code": null, "e": 21572, "s": 21503, "text": "N(s,a) : The number of times the simulation take action a in state s" }, { "code": null, "e": 21696, "s": 21572, "text": "P(s,a) : The estimate probability of taking action a in state s that is policy produced by the model of the neural network." }, { "code": null, "e": 21745, "s": 21696, "text": "Whereas the node will contain several parameter:" }, { "code": null, "e": 21884, "s": 21745, "text": "N(s) : The number of times the simulation take this state (s). It’s equal to the sum of N(s,a) for every possible action a in the state s." }, { "code": null, "e": 22023, "s": 21884, "text": "N(s) : The number of times the simulation take this state (s). It’s equal to the sum of N(s,a) for every possible action a in the state s." }, { "code": null, "e": 22263, "s": 22023, "text": "At the start of each episodes, the MCTS is initialized with a single root node. The root node is also act as a leaf node when it is initialized. From this root, the MCTS will expand the tree until the limit number of simulation is reached." }, { "code": null, "e": 22343, "s": 22263, "text": "After we initialize the tree, there are 4 steps on doing the MCTS in AlphaZero:" }, { "code": null, "e": 22379, "s": 22343, "text": "SelectExpand and EvaluateBackupPlay" }, { "code": null, "e": 22386, "s": 22379, "text": "Select" }, { "code": null, "e": 22406, "s": 22386, "text": "Expand and Evaluate" }, { "code": null, "e": 22413, "s": 22406, "text": "Backup" }, { "code": null, "e": 22418, "s": 22413, "text": "Play" }, { "code": null, "e": 22496, "s": 22418, "text": "The step 1–3 is iterated by the number of simulations and then do the step 4." }, { "code": null, "e": 22950, "s": 22496, "text": "The simulation in the MCTS will begin at the root node (s0), and finishes if the simulation encounter the leaf node sL at time step L. At each of these time steps, for every node that is already expanded in the Expand and Evaluate step, an action is selected according to the parameter in the edge of each node. Here we will select the action a in the state s which has the highest U(s,a), the Upper Confidence Bound using variant of the PUCT algorithm." }, { "code": null, "e": 23053, "s": 22950, "text": "where cpuct is a hyperparameter to determine the level of exploration. sum of N(s,b) is equal to N(s)." }, { "code": null, "e": 23140, "s": 23053, "text": "If s is s0 (root node), P(s,a) is changed to be P (s, a) = (1 — u000fe)*pa + u000fe*ηa" }, { "code": null, "e": 23314, "s": 23140, "text": "where η is probability distribution by using Dirichlet noise with the chosen parameter and e is 0.25 . This will make the exploration to try all the moves in the root state." }, { "code": null, "e": 23430, "s": 23314, "text": "This step will be done until the leaf node is found. If leaf node is found, the Expand and Evaluate step is called." }, { "code": null, "e": 23695, "s": 23430, "text": "If the current node is the leaf node, this action will be performed. We will evaluate the state sL with the representation that we have defined above to be the input of the neural network. It will output the policy and the value of evaluation of the current state." }, { "code": null, "e": 24089, "s": 23695, "text": "The input will be transformed into any identical state at random in uniform probability distribution (It can choose the unchanged one). Because we don’t have it in this game, the state won’t be transformed and the input of neural network will always be the same. so in the implemention of EvoPawness (Temporary Name), the output of function di will return the sL without transforming the form." }, { "code": null, "e": 24307, "s": 24089, "text": "The output is the policy p and the value v for the state sL explained in the previous section. If p is the action of the transformed state, the action should be transformed back to be the method of the original state." }, { "code": null, "e": 24436, "s": 24307, "text": "in p, the invalid action probability will be masked and the valid action will be normalized, so that the vector will sum to one." }, { "code": null, "e": 24582, "s": 24436, "text": "Then, the Leaf node is expanded with edge containing all possible action in that state. Each edge and the leaf node parameter is initialized to :" }, { "code": null, "e": 24683, "s": 24582, "text": "N(sL,a) = 0, Q(sL,a) = 0, N(s) = 0, P = p, P(sL,a) = paWhere a is a possible action in the state sL." }, { "code": null, "e": 24891, "s": 24683, "text": "After we expand the leaf node (sL), the parameter will be updated in a backward pass to all of the parent’s node until root node, which is through each step t ≤ L. These parameters will be updated as follow:" }, { "code": null, "e": 24983, "s": 24891, "text": "Q(st,at) = (Q(st,at)* N(st,at) + v)/ (N(st,at) + 1)N(st,at) = N(st,at) + 1N(st) = N(st) + 1" }, { "code": null, "e": 25211, "s": 24983, "text": "Note that v = v * -1 if st 's player is different than sL. for example: st’s turn is black and sL’s turn is white. Since this is a zero sum game, the evaluation of opposite player (v) will be the negative of the current player." }, { "code": null, "e": 25338, "s": 25211, "text": "After do Backup steps, do the Select step from the root node again if the maximum of number of simulation hasn’t been reached." }, { "code": null, "e": 25455, "s": 25338, "text": "These steps will be iterated until maximum of number of simulation is reached. If it has been reached, do this step:" }, { "code": null, "e": 25726, "s": 25455, "text": "At the end of the search, it is time to select the action a in the root position s0 based on the parameter updated at simulations. Probability of action a given root state (πa|s) is selected proportional to the exponentiated visit count N(s,a) counted at the simulation." }, { "code": null, "e": 25801, "s": 25726, "text": "We will calculate the policy of all the action with the following formula:" }, { "code": null, "e": 25973, "s": 25801, "text": "Where τ is a temperature that is used to control the degree of exploration. When the turn or step in the game is lower than 30, the τ is set to 1, infinitesimal otherwise." }, { "code": null, "e": 26040, "s": 25973, "text": "The high-level pseudocode implementation of the MCTS is as follow:" }, { "code": null, "e": 26078, "s": 26040, "text": "The implementation can be found here:" }, { "code": null, "e": 26089, "s": 26078, "text": "github.com" }, { "code": null, "e": 26276, "s": 26089, "text": "Note that the implementation in the repository will be different but it has the same objective. In the repository, I include select, expand, and evaluate step in the ‘expand()’ function." }, { "code": null, "e": 26551, "s": 26276, "text": "For maintaining the quality of the model, we must ensure that the model that is used is the best one. To do that, AlphaZero will compare the quality of the the current best model and the current model. It’s quite easy to do it. We need two agents that will fight each other." }, { "code": null, "e": 26830, "s": 26551, "text": "These models are pitted each other for n round by the chosen max simulation and limited by max_step to prevent the game from infinite loop that will make the terminal state unreachable. This will return the score which will determine the best model. n can be fill by any number." }, { "code": null, "e": 26989, "s": 26830, "text": "If the current model wins by a chosen margin (in the paper 55%), the best model is replaced by the current model. The best model is used for the next episode." }, { "code": null, "e": 27069, "s": 26989, "text": "If the best model wins, the best model remains to be used for the next episode." }, { "code": null, "e": 27291, "s": 27069, "text": "We will initiate 2 MCTS, one with the best model neural network and the other with current neural network. The color of the player can be decided by yourself (for example : white is best model and black is current model)." }, { "code": null, "e": 27314, "s": 27291, "text": "Here’s the pseudo code" }, { "code": null, "e": 27377, "s": 27314, "text": "The implementation can be found here (fight_agent() function):" }, { "code": null, "e": 27388, "s": 27377, "text": "github.com" }, { "code": null, "e": 27541, "s": 27388, "text": "That’s it. We have defined all the components ready for the AlphaZero. Now we will connect all of our defined components and do the AlphaZero algorithm." }, { "code": null, "e": 27625, "s": 27541, "text": "After we define all the component that will be used for the MCTS, let’s wrap it up." }, { "code": null, "e": 27719, "s": 27625, "text": "The step of implementing AlphaZero based on the components that we have defined is as follow:" }, { "code": null, "e": 28789, "s": 27719, "text": "Generate all unique actions that can be used for every players.Create the neural network model which will be used to evaluate in the MCTS with the input of the unique generated actions. The policy head in the model will adjust its output shape by the total of unique actions.Create structure data deque which will be used to keep the information about the result of every self-play and will be used to be input of the neural network. The maximum length of the deque must be defined.For every episodes, we create new instances of MCTS which will be used to train our agent by self-playing by itself. We will see this steps more detail below.After the self-play is done, train the neural network model based on the data generated from self play in the deque. The total of instances in the deque is limited to the defined maximum length of deque.After we train the model, we will check whether the current model is better than current best model. If it’s true, then change the best model into current model. The best model will be used for evaluating for the next episode." }, { "code": null, "e": 28853, "s": 28789, "text": "Generate all unique actions that can be used for every players." }, { "code": null, "e": 29066, "s": 28853, "text": "Create the neural network model which will be used to evaluate in the MCTS with the input of the unique generated actions. The policy head in the model will adjust its output shape by the total of unique actions." }, { "code": null, "e": 29274, "s": 29066, "text": "Create structure data deque which will be used to keep the information about the result of every self-play and will be used to be input of the neural network. The maximum length of the deque must be defined." }, { "code": null, "e": 29433, "s": 29274, "text": "For every episodes, we create new instances of MCTS which will be used to train our agent by self-playing by itself. We will see this steps more detail below." }, { "code": null, "e": 29637, "s": 29433, "text": "After the self-play is done, train the neural network model based on the data generated from self play in the deque. The total of instances in the deque is limited to the defined maximum length of deque." }, { "code": null, "e": 29864, "s": 29637, "text": "After we train the model, we will check whether the current model is better than current best model. If it’s true, then change the best model into current model. The best model will be used for evaluating for the next episode." }, { "code": null, "e": 29933, "s": 29864, "text": "When the step is doing the self-play, we will do the steps as below:" }, { "code": null, "e": 30020, "s": 29933, "text": "First, we need to initiate the state of the game and the MCTS. Then, do the following:" }, { "code": null, "e": 30317, "s": 30020, "text": "First, we fill the parameter inside the MCTS (self_play()), then we get the action probability on the root (play()). We fill the deque with the action, the state, and the player information. After the state reached the terminal or the max step, we finally add the reward information to the deque." }, { "code": null, "e": 30464, "s": 30317, "text": "After we fill the reward on the deque, we will append the content of the deque to the global deque which will be used to train the neural network." }, { "code": null, "e": 30528, "s": 30464, "text": "The self_play function is a MCTS simulator which acts this way:" }, { "code": null, "e": 30688, "s": 30528, "text": "That’s it, so every simulation of MCTS will simulate until leaf node is found. If it has been found, then do the expand and evaluate. If not, do the selection." }, { "code": null, "e": 30775, "s": 30688, "text": "That’s it, we have defined the how to create the AlphaZero implementation to the game." }, { "code": null, "e": 30873, "s": 30775, "text": "For the implementation, you can see the fit_train() and on the train_module.py in the repository." }, { "code": null, "e": 30884, "s": 30873, "text": "github.com" }, { "code": null, "e": 31146, "s": 30884, "text": "To run the training, use main_from_start.py for training from the start. and main_from_continue.py to train from the checkpoint. For now, I suggest that you don’t try to train the model until I’ve refactored and clean the code. I plan to do it on next Saturday." }, { "code": null, "e": 31186, "s": 31146, "text": "Below is the code of main_from_start.py" }, { "code": null, "e": 31197, "s": 31186, "text": "github.com" }, { "code": null, "e": 31267, "s": 31197, "text": "There are several lesson that I learnt on implementing the AlphaZero." }, { "code": null, "e": 32534, "s": 31267, "text": "I’ve run the code to train the model. I’ve learnt that at first, It is very hard to gain an episode which results to win or lose. It often end in draw (max steps reached). I conclude that the max simulation that I set is not enough. I need higher max simulation on the MCTS. I’ve also tried another way to solve it. I tried to hack the simulation of MCTS by letting the agent always attack the enemy. If you are confused what is greed variable inside the MCTS, for 1/8 of maximum episodes that I set and the chosen minimum step, the simulation will always make the attack action and promote action has bigger Q on the Upper Confidence Bound than other actions. This will be disabled when pitting two models. I need to find a better way to solve this problem.I need to implement multi-thread on simulating the MCTS. A single thread still can be used, but it’s very slow. So, in the next part, I will try to implement multi-thread MCTS.I haven’t tuned the hyperparameter of the neural network and MCTS. So, I still don’t know how many residual layers should I use. Currently, I use 4 residual layers. I didn’t tune it because the training is very slow 😢.Make sure to read the paper thoroughly. I’ve fixed my code several times because I skipped some part on the paper." }, { "code": null, "e": 33293, "s": 32534, "text": "I’ve run the code to train the model. I’ve learnt that at first, It is very hard to gain an episode which results to win or lose. It often end in draw (max steps reached). I conclude that the max simulation that I set is not enough. I need higher max simulation on the MCTS. I’ve also tried another way to solve it. I tried to hack the simulation of MCTS by letting the agent always attack the enemy. If you are confused what is greed variable inside the MCTS, for 1/8 of maximum episodes that I set and the chosen minimum step, the simulation will always make the attack action and promote action has bigger Q on the Upper Confidence Bound than other actions. This will be disabled when pitting two models. I need to find a better way to solve this problem." }, { "code": null, "e": 33470, "s": 33293, "text": "I need to implement multi-thread on simulating the MCTS. A single thread still can be used, but it’s very slow. So, in the next part, I will try to implement multi-thread MCTS." }, { "code": null, "e": 33689, "s": 33470, "text": "I haven’t tuned the hyperparameter of the neural network and MCTS. So, I still don’t know how many residual layers should I use. Currently, I use 4 residual layers. I didn’t tune it because the training is very slow 😢." }, { "code": null, "e": 33804, "s": 33689, "text": "Make sure to read the paper thoroughly. I’ve fixed my code several times because I skipped some part on the paper." }, { "code": null, "e": 34050, "s": 33804, "text": "In this article, we have constructed all the components that will be used to implement the AlphaZero. We also have implemented the AlphaZero algorithm. This article haven’t told the result of the AlphaZero yet since the training is not done yet." }, { "code": null, "e": 34205, "s": 34050, "text": "This article still use a single GPU on training the model. It also uses a single thread to run the simulation of MCTS. So, the training will be very slow." }, { "code": null, "e": 34415, "s": 34205, "text": "Woah, look at my 25 minutes read time article 😆. Finally the article is done and published. Thanks to the several articles that I’ve read, I can experiment the AlphaZero algorithm and understand the algorithm." }, { "code": null, "e": 34800, "s": 34415, "text": "Since the training is not done yet, I plan to create the next part that will focus on the improvement and the result of implementing AlphaZero to this game. Unfortunately, with the limited resource that I have, I’m afraid that this project will be on hold until I get a new computer to experiment it. Well, you see, I’m unemployed (for several reasons) so I have limited money here 😢." }, { "code": null, "e": 34966, "s": 34800, "text": "I will try to fix the mess of the code and make it to be executed easily next week. Currently, the code is very messy and has high verbosity when the program is run." }, { "code": null, "e": 35198, "s": 34966, "text": "I welcome any feedback that can improve myself and this article. I’m in the process of learning on writing and reinforcement learning. I really need a feedback to become better. Just make sure to give feedback in a proper manner 😄." }, { "code": null, "e": 35379, "s": 35198, "text": "Oh, I promised to tell you the details of the project structure and the GUI at the last part. Sorry, I forgot to write it 😅. If I have the time, I will write it on my next article." }, { "code": null, "e": 35607, "s": 35379, "text": "For my several next projects, I will focus on NLP or Computer Vision tasks. I will write something about using GAN on these tasks. I want to learn GAN and implement it, since it’s a hot topic in the Deep Learning at the moment." }, { "code": null, "e": 35784, "s": 35607, "text": "If you want another article from me like this one, please clap this article 👏 👏. It will boost my spirit to write my next article. I promise to make a better article about AI ." }, { "code": null, "e": 35811, "s": 35784, "text": "See ya in my next article!" }, { "code": null, "e": 35890, "s": 35811, "text": "Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1" }, { "code": null, "e": 35965, "s": 35890, "text": "Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2" }, { "code": null, "e": 36040, "s": 35965, "text": "Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3" }, { "code": null, "e": 36057, "s": 36040, "text": "web.stanford.edu" }, { "code": null, "e": 36068, "s": 36057, "text": "medium.com" }, { "code": null, "e": 36095, "s": 36068, "text": "[Source 2] by David Foster" }, { "code": null, "e": 36209, "s": 36095, "text": "[Source 3] Silver, David, et al. “Mastering the game of Go without human knowledge.” Nature 550.7676 (2017): 354." }, { "code": null, "e": 36372, "s": 36209, "text": "[Source 4] Silver, David, et al. “Mastering chess and shogi by self-play with a general reinforcement learning algorithm.” arXiv preprint arXiv:1712.01815 (2017)." } ]
How to create a Tkinter error message box?
The Tkinter library has many built-in functions and methods which can be used to implement the functional part of an application. We can use messagebox module in Tkinter to create various popup dialog boxes. The messagebox property has different types of built-in popup windows that the users can use in their applications. If you need to display the error messagebox in your application, you can use showerror("Title", "Error Message") method. This method can be invoked with the messagebox itself. # Import the required libraries from tkinter import * from tkinter import messagebox # Create an instance of tkinter frame or window win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Define a function to show the error message def on_click(): messagebox.showerror('Python Error', 'Error: This is an Error Message!') # Create a label widget label = Label(win, text="Click the button to show the message ", font=('Calibri 15 bold')) label.pack(pady=20) # Create a button to delete the button b = Button(win, text="Click Me", command=on_click) b.pack(pady=20) win.mainloop() When you run the above code, it will show a button widget and a label in the window. Click the button to show the error message.
[ { "code": null, "e": 1386, "s": 1062, "text": "The Tkinter library has many built-in functions and methods which can be used to implement the functional part of an application. We can use messagebox module in Tkinter to create various popup dialog boxes. The messagebox property has different types of built-in popup windows that the users can use in their applications." }, { "code": null, "e": 1562, "s": 1386, "text": "If you need to display the error messagebox in your application, you can use showerror(\"Title\", \"Error Message\") method. This method can be invoked with the messagebox itself." }, { "code": null, "e": 2168, "s": 1562, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import messagebox\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a function to show the error message\ndef on_click():\n messagebox.showerror('Python Error', 'Error: This is an Error Message!')\n\n# Create a label widget\nlabel = Label(win, text=\"Click the button to show the message \",\nfont=('Calibri 15 bold'))\nlabel.pack(pady=20)\n\n\n# Create a button to delete the button\nb = Button(win, text=\"Click Me\", command=on_click)\nb.pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 2297, "s": 2168, "text": "When you run the above code, it will show a button widget and a label in the window. Click the button to show the error message." } ]
Python library PyTube to download youtube videos
You know “youtube” right? Yes that most famous video sharing website especially in india . Most of the time, you like some videos and you try to download that video so as to check it later/offline. Then you come across “youtube-downloader” app to download youtube videos from the youtube website. But most of the apps comes with some restriction (if you are using it for free) or cost you money. But have you ever think of creating our own program to download youtube videos? If not you, then you should try as its very simply to do using the python library. Python provides “pytube” library to download videos from the youtube. This library allows us to download videos from the web. Pytube is not a standard library, so we need to install it. With pip, its easy to install − pip install pytube Collecting pytube Downloading https://files.pythonhosted.org/packages/af/56/c9b484e93e1f3a4ef6aefbc1e68258121831007938556daf968ab4519c9c/pytube-9.3.5-py3-none-any.whl Installing collected packages: pytube Successfully installed pytube-9.3.5 As we see down the article, downloading a youtube video using pytube is very easy. So let’s start by importing the youtube class: from pytube import YouTube Now let’s try to get a link of the video. For example, lets select a video of your choice − yt = YouTube('https://www.youtube.com/watch?v=-KnAZcXzxRA') The pytube API makes all information intuitive to access. For example, this is how you would get the video’s title: >>> yt.title 'Redmi Note 7 Fake 48MP Camera? Explained \U0001f525\U0001f525\U0001f525' And to get the thumbnail url − >>> yt.thumbnail_url 'https://i.ytimg.com/vi/-KnAZcXzxRA/default.jpg' Now, we need to select the media format. Pytube module provides following media formats to download video − >>> yt.streams.all() [<Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2">, <Stream: itag="43" mime_type="video/webm" res="360p" fps="30fps" vcodec="vp8.0" acodec="vorbis">, <Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2">, <Stream: itag="36" mime_type="video/3gpp" res="240p" fps="30fps" vcodec="mp4v.20.3" acodec="mp4a.40.2">, <Stream: itag="17" mime_type="video/3gpp" res="144p" fps="30fps" vcodec="mp4v.20.3" acodec="mp4a.40.2">, <Stream: itag="137" mime_type="video/mp4" res="1080p" fps="30fps" vcodec="avc1.640028">, <Stream: itag="248" mime_type="video/webm" res="1080p" fps="30fps" vcodec="vp9">, <Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.4d401f">, <Stream: itag="247" mime_type="video/webm" res="720p" fps="30fps" vcodec="vp9">, <Stream: itag="135" mime_type="video/mp4" res="480p" fps="30fps" vcodec="avc1.4d401f">, <Stream: itag="244" mime_type="video/webm" res="480p" fps="30fps" vcodec="vp9">, <Stream: itag="397" mime_type="video/mp4" res="None" fps="30fps" vcodec="av01.0.05M.08">, <Stream: itag="134" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.4d401e">, <Stream: itag="243" mime_type="video/webm" res="360p" fps="30fps" vcodec="vp9">, <Stream: itag="396" mime_type="video/mp4" res="None" fps="30fps" vcodec="av01.0.05M.08">, <Stream: itag="133" mime_type="video/mp4" res="240p" fps="30fps" vcodec="avc1.4d400d">, <Stream: itag="242" mime_type="video/webm" res="240p" fps="30fps" vcodec="vp9">, <Stream: itag="395" mime_type="video/mp4" res="None" fps="30fps" vcodec="av01.0.05M.08">, <Stream: itag="160" mime_type="video/mp4" res="144p" fps="30fps" vcodec="avc1.4d400c">, <Stream: itag="278" mime_type="video/webm" res="144p" fps="30fps" vcodec="vp9">, <Stream: itag="394" mime_type="video/mp4" res="None" fps="30fps" vcodec="av01.0.05M.08">, <Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2">, <Stream: itag="171" mime_type="audio/webm" abr="128kbps" acodec="vorbis">, <Stream: itag="249" mime_type="audio/webm" abr="50kbps" acodec="opus">, <Stream: itag="250" mime_type="audio/webm" abr="70kbps" acodec="opus">, <Stream: itag="251" mime_type="audio/webm" abr="160kbps" acodec="opus">] >>> </Stream:> Let’s say we want to get the first stream: >>> stream = yt.streams.first() >>> stream <Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2"> The video will be downloaded into your destination path − >>> stream.download('f:/') 'f:/Redmi Note 7 Fake 48MP Camera Explained \U0001f525\U0001f525\U0001f525.mp4' Or else you can download the video into the current working directory − >>> stream.download() 'C:\\Python\\Python361\\Redmi Note 7 Fake 48MP Camera Explained \U0001f525\U0001f525\U0001f525.mp4' Now we see the video is downloaded in our destination path:
[ { "code": null, "e": 1747, "s": 1062, "text": "You know “youtube” right? Yes that most famous video sharing website especially in india . Most of the time, you like some videos and you try to download that video so as to check it later/offline. Then you come across “youtube-downloader” app to download youtube videos from the youtube website. But most of the apps comes with some restriction (if you are using it for free) or cost you money. But have you ever think of creating our own program to download youtube videos? If not you, then you should try as its very simply to do using the python library. Python provides “pytube” library to download videos from the youtube. This library allows us to download videos from the web." }, { "code": null, "e": 1839, "s": 1747, "text": "Pytube is not a standard library, so we need to install it. With pip, its easy to install −" }, { "code": null, "e": 2099, "s": 1839, "text": "pip install pytube\nCollecting pytube\nDownloading https://files.pythonhosted.org/packages/af/56/c9b484e93e1f3a4ef6aefbc1e68258121831007938556daf968ab4519c9c/pytube-9.3.5-py3-none-any.whl\nInstalling collected packages: pytube\nSuccessfully installed pytube-9.3.5" }, { "code": null, "e": 2182, "s": 2099, "text": "As we see down the article, downloading a youtube video using pytube is very easy." }, { "code": null, "e": 2229, "s": 2182, "text": "So let’s start by importing the youtube class:" }, { "code": null, "e": 2256, "s": 2229, "text": "from pytube import YouTube" }, { "code": null, "e": 2348, "s": 2256, "text": "Now let’s try to get a link of the video. For example, lets select a video of your choice −" }, { "code": null, "e": 2408, "s": 2348, "text": "yt = YouTube('https://www.youtube.com/watch?v=-KnAZcXzxRA')" }, { "code": null, "e": 2524, "s": 2408, "text": "The pytube API makes all information intuitive to access. For example, this is how you would get the video’s title:" }, { "code": null, "e": 2611, "s": 2524, "text": ">>> yt.title\n'Redmi Note 7 Fake 48MP Camera? Explained \\U0001f525\\U0001f525\\U0001f525'" }, { "code": null, "e": 2642, "s": 2611, "text": "And to get the thumbnail url −" }, { "code": null, "e": 2712, "s": 2642, "text": ">>> yt.thumbnail_url\n'https://i.ytimg.com/vi/-KnAZcXzxRA/default.jpg'" }, { "code": null, "e": 2820, "s": 2712, "text": "Now, we need to select the media format. Pytube module provides following media formats to download video −" }, { "code": null, "e": 5122, "s": 2820, "text": ">>> yt.streams.all()\n[<Stream: itag=\"22\" mime_type=\"video/mp4\" res=\"720p\" fps=\"30fps\" vcodec=\"avc1.64001F\" acodec=\"mp4a.40.2\">, <Stream: itag=\"43\" mime_type=\"video/webm\" res=\"360p\" fps=\"30fps\" vcodec=\"vp8.0\" acodec=\"vorbis\">, <Stream: itag=\"18\" mime_type=\"video/mp4\" res=\"360p\" fps=\"30fps\" vcodec=\"avc1.42001E\" acodec=\"mp4a.40.2\">, <Stream: itag=\"36\" mime_type=\"video/3gpp\" res=\"240p\" fps=\"30fps\" vcodec=\"mp4v.20.3\" acodec=\"mp4a.40.2\">, <Stream: itag=\"17\" mime_type=\"video/3gpp\" res=\"144p\" fps=\"30fps\" vcodec=\"mp4v.20.3\" acodec=\"mp4a.40.2\">, <Stream: itag=\"137\" mime_type=\"video/mp4\" res=\"1080p\" fps=\"30fps\" vcodec=\"avc1.640028\">, <Stream: itag=\"248\" mime_type=\"video/webm\" res=\"1080p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"136\" mime_type=\"video/mp4\" res=\"720p\" fps=\"30fps\" vcodec=\"avc1.4d401f\">, <Stream: itag=\"247\" mime_type=\"video/webm\" res=\"720p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"135\" mime_type=\"video/mp4\" res=\"480p\" fps=\"30fps\" vcodec=\"avc1.4d401f\">, <Stream: itag=\"244\" mime_type=\"video/webm\" res=\"480p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"397\" mime_type=\"video/mp4\" res=\"None\" fps=\"30fps\" vcodec=\"av01.0.05M.08\">, <Stream: itag=\"134\" mime_type=\"video/mp4\" res=\"360p\" fps=\"30fps\" vcodec=\"avc1.4d401e\">, <Stream: itag=\"243\" mime_type=\"video/webm\" res=\"360p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"396\" mime_type=\"video/mp4\" res=\"None\" fps=\"30fps\" vcodec=\"av01.0.05M.08\">, <Stream: itag=\"133\" mime_type=\"video/mp4\" res=\"240p\" fps=\"30fps\" vcodec=\"avc1.4d400d\">, <Stream: itag=\"242\" mime_type=\"video/webm\" res=\"240p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"395\" mime_type=\"video/mp4\" res=\"None\" fps=\"30fps\" vcodec=\"av01.0.05M.08\">, <Stream: itag=\"160\" mime_type=\"video/mp4\" res=\"144p\" fps=\"30fps\" vcodec=\"avc1.4d400c\">, <Stream: itag=\"278\" mime_type=\"video/webm\" res=\"144p\" fps=\"30fps\" vcodec=\"vp9\">, <Stream: itag=\"394\" mime_type=\"video/mp4\" res=\"None\" fps=\"30fps\" vcodec=\"av01.0.05M.08\">, <Stream: itag=\"140\" mime_type=\"audio/mp4\" abr=\"128kbps\" acodec=\"mp4a.40.2\">, <Stream: itag=\"171\" mime_type=\"audio/webm\" abr=\"128kbps\" acodec=\"vorbis\">, <Stream: itag=\"249\" mime_type=\"audio/webm\" abr=\"50kbps\" acodec=\"opus\">, <Stream: itag=\"250\" mime_type=\"audio/webm\" abr=\"70kbps\" acodec=\"opus\">, <Stream: itag=\"251\" mime_type=\"audio/webm\" abr=\"160kbps\" acodec=\"opus\">]\n>>>\n</Stream:>" }, { "code": null, "e": 5165, "s": 5122, "text": "Let’s say we want to get the first stream:" }, { "code": null, "e": 5313, "s": 5165, "text": ">>> stream = yt.streams.first()\n>>> stream\n<Stream: itag=\"22\" mime_type=\"video/mp4\" res=\"720p\" fps=\"30fps\" vcodec=\"avc1.64001F\" acodec=\"mp4a.40.2\">" }, { "code": null, "e": 5371, "s": 5313, "text": "The video will be downloaded into your destination path −" }, { "code": null, "e": 5478, "s": 5371, "text": ">>> stream.download('f:/')\n'f:/Redmi Note 7 Fake 48MP Camera Explained \\U0001f525\\U0001f525\\U0001f525.mp4'" }, { "code": null, "e": 5550, "s": 5478, "text": "Or else you can download the video into the current working directory −" }, { "code": null, "e": 5672, "s": 5550, "text": ">>> stream.download()\n'C:\\\\Python\\\\Python361\\\\Redmi Note 7 Fake 48MP Camera Explained \\U0001f525\\U0001f525\\U0001f525.mp4'" }, { "code": null, "e": 5732, "s": 5672, "text": "Now we see the video is downloaded in our destination path:" } ]
What happens when a function is called before its declaration in C?
If we do not use some function prototypes, and the function body is declared in some section which is present after the calling statement of that function. In such a case, the compiler thinks that the default return type is an integer. But if the function returns some other type of value, it returns an error. If the return type is also an integer, then it will work fine, sometimes this may generate some warnings. #include<stdio.h> main() { printf("The returned value: %d\n", function); } char function() { return 'T'; //return T as character } [Error] conflicting types for 'function' [Note] previous implicit declaration of 'function' was here Now if the return type is an integer, then it will work. #include<stdio.h> main() { printf("The returned value: %d\n", function()); } int function() { return 86; //return an integer value } The returned value: 86
[ { "code": null, "e": 1479, "s": 1062, "text": "If we do not use some function prototypes, and the function body is declared in some section which is present after the calling statement of that function. In such a case, the compiler thinks that the default return type is an integer. But if the function returns some other type of value, it returns an error. If the return type is also an integer, then it will work fine, sometimes this may generate some warnings." }, { "code": null, "e": 1616, "s": 1479, "text": "#include<stdio.h>\nmain() {\n printf(\"The returned value: %d\\n\", function);\n}\nchar function() {\n return 'T'; //return T as character\n}" }, { "code": null, "e": 1717, "s": 1616, "text": "[Error] conflicting types for 'function'\n[Note] previous implicit declaration of 'function' was here" }, { "code": null, "e": 1774, "s": 1717, "text": "Now if the return type is an integer, then it will work." }, { "code": null, "e": 1913, "s": 1774, "text": "#include<stdio.h>\nmain() {\n printf(\"The returned value: %d\\n\", function());\n}\nint function() {\n return 86; //return an integer value\n}" }, { "code": null, "e": 1936, "s": 1913, "text": "The returned value: 86" } ]
Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
02 Feb, 2022 Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST. Examples: Input: Root of following BST 5 / \ 2 13 Output: The given BST is converted to following Binary Tree 18 / \ 20 13 Method 1:Solution: Do reverse In order traversal. Keep track of the sum of nodes visited so far. Let this sum be sum. For every node currently being visited, first add the key of this node to sum, i.e. sum = sum + node->key. Then change the key of current node to sum, i.e., node->key = sum. When a BST is being traversed in reverse In order, for every key currently being visited, all keys that are already visited are all greater keys. C++ C Java Python3 C# Javascript // C++ Program to change a BST to Binary Tree// such that key of a node becomes original// key plus sum of all greater keys in BST#include <bits/stdc++.h>using namespace std; /* A BST node has key, left child and right child */struct node{ int key; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given key and NULL left and right pointers.*/struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node);} // A recursive function that traverses the// given BST in reverse inorder and for// every key, adds all greater keys to itvoid addGreaterUtil(struct node *root, int *sum_ptr){ // Base Case if (root == NULL) return; // Recur for right subtree first so that sum // of all greater nodes is stored at sum_ptr addGreaterUtil(root->right, sum_ptr); // Update the value at sum_ptr *sum_ptr = *sum_ptr + root->key; // Update key of this node root->key = *sum_ptr; // Recur for left subtree so that the // updated sum is added to smaller nodes addGreaterUtil(root->left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes// sum and calls addGreaterUtil() to recursively// update and use value of sumvoid addGreater(struct node *root){ int sum = 0; addGreaterUtil(root, &sum);} // A utility function to print inorder// traversal of Binary Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); cout << node->key << " " ; printInorder(node->right);} // Driver Codeint main(){ /* Create following BST 5 / \ 2 13 */ node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); cout << "Inorder traversal of the " << "given tree" << endl; printInorder(root); addGreater(root); cout << endl; cout << "Inorder traversal of the " << "modified tree" << endl; printInorder(root); return 0;} // This code is contributed by SHUBHAMSINGH10 // Program to change a BST to Binary Tree such that key of a node becomes// original key plus sum of all greater keys in BST#include <stdio.h>#include <stdlib.h> /* A BST node has key, left child and right child */struct node{ int key; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node);} // A recursive function that traverses the given BST in reverse inorder and// for every key, adds all greater keys to itvoid addGreaterUtil(struct node *root, int *sum_ptr){ // Base Case if (root == NULL) return; // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(root->right, sum_ptr); // Update the value at sum_ptr *sum_ptr = *sum_ptr + root->key; // Update key of this node root->key = *sum_ptr; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(root->left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes sum and calls// addGreaterUtil() to recursivel upodate and use value of sumvoid addGreater(struct node *root){ int sum = 0; addGreaterUtil(root, &sum);} // A utility function to print inorder traversal of Binary Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->key); printInorder(node->right);} // Driver program to test above functionint main(){ /* Create following BST 5 / \ 2 13 */ node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); printf("Inorder traversal of the given tree\n"); printInorder(root); addGreater(root); printf("\nInorder traversal of the modified tree\n"); printInorder(root); return 0;} // Java program to convert BST to binary tree such that sum of// all greater keys is added to every key class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Sum { int sum = 0;} class BinaryTree { static Node root; Sum summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and // for every key, adds all greater keys to it void addGreaterUtil(Node node, Sum sum_ptr) { // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr); } // A wrapper over addGreaterUtil(). It initializes sum and calls // addGreaterUtil() to recursivel upodate and use value of sum Node addGreater(Node node) { addGreaterUtil(node, summ); return node; } // A utility function to print inorder traversal of Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver program to test the above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(13); System.out.println("Inorder traversal of given tree "); tree.printInorder(root); Node node = tree.addGreater(root); System.out.println(""); System.out.println("Inorder traversal of modified tree "); tree.printInorder(node); }} // This code has been contributed by Mayank Jaiswal # Python3 Program to change a BST to# Binary Tree such that key of a node# becomes original key plus sum of all# greater keys in BST # A BST node has key, left child and# right child */class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A recursive function that traverses# the given BST in reverse inorder and# for every key, adds all greater keys to itdef addGreaterUtil(root, sum_ptr): # Base Case if root == None: return # Recur for right subtree first so that sum # of all greater nodes is stored at sum_ptr addGreaterUtil(root.right, sum_ptr) # Update the value at sum_ptr sum_ptr[0] = sum_ptr[0] + root.key # Update key of this node root.key = sum_ptr[0] # Recur for left subtree so that the # updated sum is added to smaller nodes addGreaterUtil(root.left, sum_ptr) # A wrapper over addGreaterUtil(). It initializes# sum and calls addGreaterUtil() to recursive# update and use value of sumdef addGreater(root): Sum = [0] addGreaterUtil(root, Sum) # A utility function to print inorder# traversal of Binary Treedef printInorder(node): if node == None: return printInorder(node.left) print(node.key, end = " ") printInorder(node.right) # Driver Codeif __name__ == '__main__': # Create following BST # 5 # / \ # 2 13 root = Node(5) root.left = Node(2) root.right = Node(13) print("Inorder traversal of the given tree") printInorder(root) addGreater(root) print() print("Inorder traversal of the modified tree") printInorder(root) # This code is contributed by PranchalK using System; // C# program to convert BST to binary tree such that sum of // all greater keys is added to every key public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Sum{ public int sum = 0;} public class BinaryTree{ public static Node root; public Sum summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and // for every key, adds all greater keys to it public virtual void addGreaterUtil(Node node, Sum sum_ptr) { // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr); } // A wrapper over addGreaterUtil(). It initializes sum and calls // addGreaterUtil() to recursivel upodate and use value of sum public virtual Node addGreater(Node node) { addGreaterUtil(node, summ); return node; } // A utility function to print inorder traversal of Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(5); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(13); Console.WriteLine("Inorder traversal of given tree "); tree.printInorder(root); Node node = tree.addGreater(root); Console.WriteLine(""); Console.WriteLine("Inorder traversal of modified tree "); tree.printInorder(node); }} // This code is contributed by Shrikant13 <script> // Javascript program to convert BST to binary tree such that sum of // all greater keys is added to every keyclass Node{ constructor(d){ this.data = d; this.left = null; this.right = null;}} class Sum{ constructor() { this.sum = 0; }} var root = null;var summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and// for every key, adds all greater keys to itfunction addGreaterUtil(node, sum_ptr){ // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes sum and calls// addGreaterUtil() to recursivel upodate and use value of sumfunction addGreater(node){ addGreaterUtil(node, summ); return node;} // A utility function to print inorder traversal of Binary Treefunction printInorder(node){ if (node == null) { return; } printInorder(node.left); document.write(node.data + " "); printInorder(node.right);} // Driver program to test the above functionsroot = new Node(5);root.left = new Node(2);root.right = new Node(13);document.write("Inorder traversal of given tree <br>");printInorder(root);var node = addGreater(root);document.write("<br>");document.write("Inorder traversal of modified tree <br>");printInorder(node); // This code is contributed by rrrtnx.</script> Output: Inorder traversal of the given tree 2 5 13 Inorder traversal of the modified tree 20 18 13 Time Complexity: O(n) where n is the number of nodes in given Binary Search Tree. Method 2: The below method uses the technique of Iteration with the Stack. Approach: First, we initialize an empty stack and set the current node to the root.Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack.. Next, we visit the node on the top of our stack and consider its left subtree.Eventually, our stack is empty and the node points to the left null child of the tree’s minimum value node, so the loop terminates. First, we initialize an empty stack and set the current node to the root. Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack. . Next, we visit the node on the top of our stack and consider its left subtree. Eventually, our stack is empty and the node points to the left null child of the tree’s minimum value node, so the loop terminates. Below is the implementation of the above approach: C C++ Java Python3 C# Javascript #include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree tNode has data, pointer to left childand a pointer to right child */struct tNode { int data; struct tNode* left; struct tNode* right;}; /* Structure of a stack node. Linked List implementation isused for stack. A stack node contains a pointer to tree nodeand a pointer to next stack node */struct sNode { struct tNode* t; struct sNode* next;}; /* Stack related functions */void push(struct sNode** top_ref, struct tNode* t);struct tNode* pop(struct sNode** top_ref);bool isEmpty(struct sNode* top); /* Iterative function for inorder tree traversal */void inOrder(struct tNode* root){ /* set current to root of binary tree */ struct tNode* current = root; struct sNode* s = NULL; /* Initialize stack s */ bool done = 0; while (!done) { /* Reach the left most tNode of the current tNode */ if (current != NULL) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ push(&s, current); current = current->left; } /* backtrack from the empty subtree and visit the tNode at the top of the stack; however, if the stack is empty, you are done */ else { if (!isEmpty(s)) { current = pop(&s); printf("%d ", current->data); /* we have visited the node and its left subtree. Now, it's right subtree's turn */ current = current->right; } else done = 1; } } /* end of while */} void Greater_BST(struct tNode* root){ int sum = 0; struct sNode* st = NULL; struct tNode* node = root; while (!isEmpty(st) || node != NULL) { // push all nodes up to (and including) this // subtree's maximum on the stack while (node != NULL) { push(&st, node); node = node->right; } node = pop(&st); sum += node->data; node->data = sum; // all nodes with values between the current and its // parent lie in the left subtree. node = node->left; }} /* UTILITY FUNCTIONS *//* Function to push an item to sNode*/void push(struct sNode** top_ref, struct tNode* t){ /* allocate tNode */ struct sNode* new_tNode = (struct sNode*)malloc(sizeof(struct sNode)); if (new_tNode == NULL) { printf("Stack Overflow \n"); getchar(); exit(0); } /* put in the data */ new_tNode->t = t; /* link the old list off the new tNode */ new_tNode->next = (*top_ref); /* move the head to point to the new tNode */ (*top_ref) = new_tNode;} /* The function returns true if stack is empty, otherwise * false */bool isEmpty(struct sNode* top){ return (top == NULL) ? 1 : 0;} /* Function to pop an item from stack*/struct tNode* pop(struct sNode** top_ref){ struct tNode* res; struct sNode* top; top = *top_ref; res = top->t; *top_ref = top->next; free(top); return res;} /* Helper function that allocates a new tNode with thegiven data and NULL left and right pointers. */struct tNode* newtNode(int data){ struct tNode* tNode = (struct tNode*)malloc(sizeof(struct tNode)); tNode->data = data; tNode->left = NULL; tNode->right = NULL; return (tNode);} /* Driver program to test above functions*/int main(){ /* Let us create following BST 8 / \ 5 12 / \ / \ 2 7 9 15 */ struct tNode* root = newtNode(8); root->left = newtNode(5); root->right = newtNode(12); root->left->left = newtNode(2); root->left->right = newtNode(7); root->right->left = newtNode(9); root->right->right = newtNode(15); Greater_BST(root); inOrder(root); getchar(); return 0;} // C++ program to add all greater// values in every node of BST through Iteration using Stack#include <bits/stdc++.h>using namespace std; class Node {public: int data; Node *left, *right;}; // A utility function to create// a new BST nodeNode* newNode(int item){ Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp;} // Iterative function to add// all greater values in every nodevoid Greater_BST(Node* root){ int sum = 0; stack<Node*> st; Node* node = root; while(!st.empty() || node != NULL ){ // push all nodes up to (and including) this subtree's maximum on the stack while(node != NULL){ st.push(node); node = node->right; } node = st.top(); st.pop(); sum += node->data; node->data = sum; // all nodes with values between the current and its parent lie in the left subtree. node = node->left; }} // A utility function to do// inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); }} /* A utility function to inserta new node with given data in BST */Node* insert(Node* node, int data){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(data); /* Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node;} // Driver codeint main(){ /* Let us create following BST 8 / \ 5 12 / \ / \ 2 7 9 15 */ Node* root = NULL; root = insert(root, 8); insert(root, 5); insert(root, 2); insert(root, 7); insert(root, 12); insert(root, 9); insert(root, 15); Greater_BST(root); // print inorder traversal of the Greater BST inorder(root); return 0;} // Java code to add all greater values to// every node in a given BST import java.util.*; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); System.out.print(node.data + " "); inorderUtil(node.right); } // adding new node public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node void Greater_BST(Node root) { int sum = 0; Node node = root; Stack<Node> stack = new Stack<Node>(); while (!stack.isEmpty() || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.add(node); node = node.right; } node = stack.pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 8 / \ 5 12 / \ / \ 2 7 9 15 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(7); tree.insert(12); tree.insert(9); tree.insert(15); tree.Greater_BST(tree.root); // print inorder traversal of the Greater BST tree.inorder(); }} # Python3 program to add all greater values# in every node of BST through Iteration using Stack # A utility function to create a# new BST nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative function to add all greater# values in every node def Greater_BST(root): total = 0 node = root stack = [] while stack or node is not None: # push all nodes up to (and including) # this subtree's maximum on # the stack. while node is not None: stack.append(node) node = node.right node = stack.pop() total += node.data node.data = total # all nodes with values between # the current and its parent lie in # the left subtree. node = node.left # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.data, end =" ") inorder(root.right) # A utility function to insert a new node# with given data in BSTdef insert(node, data): # If the tree is empty, return a new node if node == None: return newNode(data) # Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 8 # / \ # 5 12 # / \ / \ # 2 7 9 15 root = None root = insert(root, 8) insert(root, 5) insert(root, 2) insert(root, 7) insert(root, 9) insert(root, 12) insert(root, 15) Greater_BST(root) # print inorder traversal of the # Greater BST inorder(root) // C# code to add all greater values to// every node in a given BSTusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); Console.Write(node.data + " "); inorderUtil(node.right); } // adding new node public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node void Greater_BST(Node root) { int sum = 0; Node node = root; Stack<Node> stack = new Stack<Node>(); while (stack.Count!=0 || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.Push(node); node = node.right; } node = stack.Pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 8 / \ 5 12 / \ / \ 2 7 9 15 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(7); tree.insert(12); tree.insert(9); tree.insert(15); tree.Greater_BST(tree.root); // print inorder traversal of the Greater BST tree.inorder(); }} // This code is contributed by Rajput-Ji <script>// javascript code to add all greater values to// every node in a given BST// A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // Inorder traversal of the tree function inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree function inorderUtil(node) { if (node == null) return; inorderUtil(node.left); document.write(node.data + " "); inorderUtil(node.right); } // adding new node function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ function insertRec(node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node function Greater_BST(root) { var sum = 0; var node = root; var stack = []; while (stack.length!= 0 || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.push(node); node = node.right; } node = stack.pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function /* * Let us create following BST * 8 / \ 5 12 / \ / \ 2 7 9 15 */ insert(8); insert(5); insert(2); insert(7); insert(12); insert(9); insert(15); Greater_BST(root); // print inorder traversal of the Greater BST inorder(); // This code is contributed by Rajput-Ji</script> Output: 58 56 51 44 36 27 15 Time Complexity: O(n) , n is no.of Node in a BST. Auxiliary Space: O(n). Stack is used for storing data. YouTubeGeeksforGeeks501K subscribersConvert a BST to a Binary Tree so that sum of greater keys is added to every key | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9zAPzXK5EaU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbkPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 PranchalKatiyar SHUBHAMSINGH10 aksrathod07 anikakapoor rrrtnx saurabh1990aror Rajput-Ji sweetyty Amazon BST Binary Search Tree Amazon Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Red-Black Tree | Set 2 (Insert) Inorder Successor in Binary Search Tree Optimal Binary Search Tree | DP-24 Find the node with minimum value in a Binary Search Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Advantages of BST over Hash Table Lowest Common Ancestor in a Binary Search Tree. Difference between Binary Tree and Binary Search Tree Find k-th smallest element in BST (Order Statistics in BST) Inorder predecessor and successor for a given key in BST
[ { "code": null, "e": 25246, "s": 25218, "text": "\n02 Feb, 2022" }, { "code": null, "e": 25414, "s": 25246, "text": "Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST. Examples: " }, { "code": null, "e": 25613, "s": 25414, "text": "Input: Root of following BST\n 5\n / \\\n 2 13\n\nOutput: The given BST is converted to following Binary Tree\n 18\n / \\\n 20 13" }, { "code": null, "e": 26052, "s": 25613, "text": "Method 1:Solution: Do reverse In order traversal. Keep track of the sum of nodes visited so far. Let this sum be sum. For every node currently being visited, first add the key of this node to sum, i.e. sum = sum + node->key. Then change the key of current node to sum, i.e., node->key = sum. When a BST is being traversed in reverse In order, for every key currently being visited, all keys that are already visited are all greater keys. " }, { "code": null, "e": 26056, "s": 26052, "text": "C++" }, { "code": null, "e": 26058, "s": 26056, "text": "C" }, { "code": null, "e": 26063, "s": 26058, "text": "Java" }, { "code": null, "e": 26071, "s": 26063, "text": "Python3" }, { "code": null, "e": 26074, "s": 26071, "text": "C#" }, { "code": null, "e": 26085, "s": 26074, "text": "Javascript" }, { "code": "// C++ Program to change a BST to Binary Tree// such that key of a node becomes original// key plus sum of all greater keys in BST#include <bits/stdc++.h>using namespace std; /* A BST node has key, left child and right child */struct node{ int key; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given key and NULL left and right pointers.*/struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node);} // A recursive function that traverses the// given BST in reverse inorder and for// every key, adds all greater keys to itvoid addGreaterUtil(struct node *root, int *sum_ptr){ // Base Case if (root == NULL) return; // Recur for right subtree first so that sum // of all greater nodes is stored at sum_ptr addGreaterUtil(root->right, sum_ptr); // Update the value at sum_ptr *sum_ptr = *sum_ptr + root->key; // Update key of this node root->key = *sum_ptr; // Recur for left subtree so that the // updated sum is added to smaller nodes addGreaterUtil(root->left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes// sum and calls addGreaterUtil() to recursively// update and use value of sumvoid addGreater(struct node *root){ int sum = 0; addGreaterUtil(root, &sum);} // A utility function to print inorder// traversal of Binary Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); cout << node->key << \" \" ; printInorder(node->right);} // Driver Codeint main(){ /* Create following BST 5 / \\ 2 13 */ node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); cout << \"Inorder traversal of the \" << \"given tree\" << endl; printInorder(root); addGreater(root); cout << endl; cout << \"Inorder traversal of the \" << \"modified tree\" << endl; printInorder(root); return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 28202, "s": 26085, "text": null }, { "code": "// Program to change a BST to Binary Tree such that key of a node becomes// original key plus sum of all greater keys in BST#include <stdio.h>#include <stdlib.h> /* A BST node has key, left child and right child */struct node{ int key; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node);} // A recursive function that traverses the given BST in reverse inorder and// for every key, adds all greater keys to itvoid addGreaterUtil(struct node *root, int *sum_ptr){ // Base Case if (root == NULL) return; // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(root->right, sum_ptr); // Update the value at sum_ptr *sum_ptr = *sum_ptr + root->key; // Update key of this node root->key = *sum_ptr; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(root->left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes sum and calls// addGreaterUtil() to recursivel upodate and use value of sumvoid addGreater(struct node *root){ int sum = 0; addGreaterUtil(root, &sum);} // A utility function to print inorder traversal of Binary Treevoid printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->key); printInorder(node->right);} // Driver program to test above functionint main(){ /* Create following BST 5 / \\ 2 13 */ node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); printf(\"Inorder traversal of the given tree\\n\"); printInorder(root); addGreater(root); printf(\"\\nInorder traversal of the modified tree\\n\"); printInorder(root); return 0;}", "e": 30240, "s": 28202, "text": null }, { "code": "// Java program to convert BST to binary tree such that sum of// all greater keys is added to every key class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class Sum { int sum = 0;} class BinaryTree { static Node root; Sum summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and // for every key, adds all greater keys to it void addGreaterUtil(Node node, Sum sum_ptr) { // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr); } // A wrapper over addGreaterUtil(). It initializes sum and calls // addGreaterUtil() to recursivel upodate and use value of sum Node addGreater(Node node) { addGreaterUtil(node, summ); return node; } // A utility function to print inorder traversal of Binary Tree void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver program to test the above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(5); tree.root.left = new Node(2); tree.root.right = new Node(13); System.out.println(\"Inorder traversal of given tree \"); tree.printInorder(root); Node node = tree.addGreater(root); System.out.println(\"\"); System.out.println(\"Inorder traversal of modified tree \"); tree.printInorder(node); }} // This code has been contributed by Mayank Jaiswal", "e": 32321, "s": 30240, "text": null }, { "code": "# Python3 Program to change a BST to# Binary Tree such that key of a node# becomes original key plus sum of all# greater keys in BST # A BST node has key, left child and# right child */class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A recursive function that traverses# the given BST in reverse inorder and# for every key, adds all greater keys to itdef addGreaterUtil(root, sum_ptr): # Base Case if root == None: return # Recur for right subtree first so that sum # of all greater nodes is stored at sum_ptr addGreaterUtil(root.right, sum_ptr) # Update the value at sum_ptr sum_ptr[0] = sum_ptr[0] + root.key # Update key of this node root.key = sum_ptr[0] # Recur for left subtree so that the # updated sum is added to smaller nodes addGreaterUtil(root.left, sum_ptr) # A wrapper over addGreaterUtil(). It initializes# sum and calls addGreaterUtil() to recursive# update and use value of sumdef addGreater(root): Sum = [0] addGreaterUtil(root, Sum) # A utility function to print inorder# traversal of Binary Treedef printInorder(node): if node == None: return printInorder(node.left) print(node.key, end = \" \") printInorder(node.right) # Driver Codeif __name__ == '__main__': # Create following BST # 5 # / \\ # 2 13 root = Node(5) root.left = Node(2) root.right = Node(13) print(\"Inorder traversal of the given tree\") printInorder(root) addGreater(root) print() print(\"Inorder traversal of the modified tree\") printInorder(root) # This code is contributed by PranchalK", "e": 34045, "s": 32321, "text": null }, { "code": "using System; // C# program to convert BST to binary tree such that sum of // all greater keys is added to every key public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class Sum{ public int sum = 0;} public class BinaryTree{ public static Node root; public Sum summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and // for every key, adds all greater keys to it public virtual void addGreaterUtil(Node node, Sum sum_ptr) { // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr); } // A wrapper over addGreaterUtil(). It initializes sum and calls // addGreaterUtil() to recursivel upodate and use value of sum public virtual Node addGreater(Node node) { addGreaterUtil(node, summ); return node; } // A utility function to print inorder traversal of Binary Tree public virtual void printInorder(Node node) { if (node == null) { return; } printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(5); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(13); Console.WriteLine(\"Inorder traversal of given tree \"); tree.printInorder(root); Node node = tree.addGreater(root); Console.WriteLine(\"\"); Console.WriteLine(\"Inorder traversal of modified tree \"); tree.printInorder(node); }} // This code is contributed by Shrikant13", "e": 36277, "s": 34045, "text": null }, { "code": "<script> // Javascript program to convert BST to binary tree such that sum of // all greater keys is added to every keyclass Node{ constructor(d){ this.data = d; this.left = null; this.right = null;}} class Sum{ constructor() { this.sum = 0; }} var root = null;var summ = new Sum(); // A recursive function that traverses the given BST in reverse inorder and// for every key, adds all greater keys to itfunction addGreaterUtil(node, sum_ptr){ // Base Case if (node == null) { return; } // Recur for right subtree first so that sum of all greater // nodes is stored at sum_ptr addGreaterUtil(node.right, sum_ptr); // Update the value at sum_ptr sum_ptr.sum = sum_ptr.sum + node.data; // Update key of this node node.data = sum_ptr.sum; // Recur for left subtree so that the updated sum is added // to smaller nodes addGreaterUtil(node.left, sum_ptr);} // A wrapper over addGreaterUtil(). It initializes sum and calls// addGreaterUtil() to recursivel upodate and use value of sumfunction addGreater(node){ addGreaterUtil(node, summ); return node;} // A utility function to print inorder traversal of Binary Treefunction printInorder(node){ if (node == null) { return; } printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right);} // Driver program to test the above functionsroot = new Node(5);root.left = new Node(2);root.right = new Node(13);document.write(\"Inorder traversal of given tree <br>\");printInorder(root);var node = addGreater(root);document.write(\"<br>\");document.write(\"Inorder traversal of modified tree <br>\");printInorder(node); // This code is contributed by rrrtnx.</script>", "e": 38024, "s": 36277, "text": null }, { "code": null, "e": 38033, "s": 38024, "text": "Output: " }, { "code": null, "e": 38124, "s": 38033, "text": "Inorder traversal of the given tree\n2 5 13\nInorder traversal of the modified tree\n20 18 13" }, { "code": null, "e": 38206, "s": 38124, "text": "Time Complexity: O(n) where n is the number of nodes in given Binary Search Tree." }, { "code": null, "e": 38216, "s": 38206, "text": "Method 2:" }, { "code": null, "e": 38281, "s": 38216, "text": "The below method uses the technique of Iteration with the Stack." }, { "code": null, "e": 38291, "s": 38281, "text": "Approach:" }, { "code": null, "e": 38745, "s": 38291, "text": "First, we initialize an empty stack and set the current node to the root.Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack.. Next, we visit the node on the top of our stack and consider its left subtree.Eventually, our stack is empty and the node points to the left null child of the tree’s minimum value node, so the loop terminates." }, { "code": null, "e": 38819, "s": 38745, "text": "First, we initialize an empty stack and set the current node to the root." }, { "code": null, "e": 38989, "s": 38819, "text": "Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack." }, { "code": null, "e": 39070, "s": 38989, "text": ". Next, we visit the node on the top of our stack and consider its left subtree." }, { "code": null, "e": 39202, "s": 39070, "text": "Eventually, our stack is empty and the node points to the left null child of the tree’s minimum value node, so the loop terminates." }, { "code": null, "e": 39253, "s": 39202, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 39255, "s": 39253, "text": "C" }, { "code": null, "e": 39259, "s": 39255, "text": "C++" }, { "code": null, "e": 39264, "s": 39259, "text": "Java" }, { "code": null, "e": 39272, "s": 39264, "text": "Python3" }, { "code": null, "e": 39275, "s": 39272, "text": "C#" }, { "code": null, "e": 39286, "s": 39275, "text": "Javascript" }, { "code": "#include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree tNode has data, pointer to left childand a pointer to right child */struct tNode { int data; struct tNode* left; struct tNode* right;}; /* Structure of a stack node. Linked List implementation isused for stack. A stack node contains a pointer to tree nodeand a pointer to next stack node */struct sNode { struct tNode* t; struct sNode* next;}; /* Stack related functions */void push(struct sNode** top_ref, struct tNode* t);struct tNode* pop(struct sNode** top_ref);bool isEmpty(struct sNode* top); /* Iterative function for inorder tree traversal */void inOrder(struct tNode* root){ /* set current to root of binary tree */ struct tNode* current = root; struct sNode* s = NULL; /* Initialize stack s */ bool done = 0; while (!done) { /* Reach the left most tNode of the current tNode */ if (current != NULL) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ push(&s, current); current = current->left; } /* backtrack from the empty subtree and visit the tNode at the top of the stack; however, if the stack is empty, you are done */ else { if (!isEmpty(s)) { current = pop(&s); printf(\"%d \", current->data); /* we have visited the node and its left subtree. Now, it's right subtree's turn */ current = current->right; } else done = 1; } } /* end of while */} void Greater_BST(struct tNode* root){ int sum = 0; struct sNode* st = NULL; struct tNode* node = root; while (!isEmpty(st) || node != NULL) { // push all nodes up to (and including) this // subtree's maximum on the stack while (node != NULL) { push(&st, node); node = node->right; } node = pop(&st); sum += node->data; node->data = sum; // all nodes with values between the current and its // parent lie in the left subtree. node = node->left; }} /* UTILITY FUNCTIONS *//* Function to push an item to sNode*/void push(struct sNode** top_ref, struct tNode* t){ /* allocate tNode */ struct sNode* new_tNode = (struct sNode*)malloc(sizeof(struct sNode)); if (new_tNode == NULL) { printf(\"Stack Overflow \\n\"); getchar(); exit(0); } /* put in the data */ new_tNode->t = t; /* link the old list off the new tNode */ new_tNode->next = (*top_ref); /* move the head to point to the new tNode */ (*top_ref) = new_tNode;} /* The function returns true if stack is empty, otherwise * false */bool isEmpty(struct sNode* top){ return (top == NULL) ? 1 : 0;} /* Function to pop an item from stack*/struct tNode* pop(struct sNode** top_ref){ struct tNode* res; struct sNode* top; top = *top_ref; res = top->t; *top_ref = top->next; free(top); return res;} /* Helper function that allocates a new tNode with thegiven data and NULL left and right pointers. */struct tNode* newtNode(int data){ struct tNode* tNode = (struct tNode*)malloc(sizeof(struct tNode)); tNode->data = data; tNode->left = NULL; tNode->right = NULL; return (tNode);} /* Driver program to test above functions*/int main(){ /* Let us create following BST 8 / \\ 5 12 / \\ / \\ 2 7 9 15 */ struct tNode* root = newtNode(8); root->left = newtNode(5); root->right = newtNode(12); root->left->left = newtNode(2); root->left->right = newtNode(7); root->right->left = newtNode(9); root->right->right = newtNode(15); Greater_BST(root); inOrder(root); getchar(); return 0;}", "e": 43204, "s": 39286, "text": null }, { "code": "// C++ program to add all greater// values in every node of BST through Iteration using Stack#include <bits/stdc++.h>using namespace std; class Node {public: int data; Node *left, *right;}; // A utility function to create// a new BST nodeNode* newNode(int item){ Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp;} // Iterative function to add// all greater values in every nodevoid Greater_BST(Node* root){ int sum = 0; stack<Node*> st; Node* node = root; while(!st.empty() || node != NULL ){ // push all nodes up to (and including) this subtree's maximum on the stack while(node != NULL){ st.push(node); node = node->right; } node = st.top(); st.pop(); sum += node->data; node->data = sum; // all nodes with values between the current and its parent lie in the left subtree. node = node->left; }} // A utility function to do// inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << \" \"; inorder(root->right); }} /* A utility function to inserta new node with given data in BST */Node* insert(Node* node, int data){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(data); /* Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node;} // Driver codeint main(){ /* Let us create following BST 8 / \\ 5 12 / \\ / \\ 2 7 9 15 */ Node* root = NULL; root = insert(root, 8); insert(root, 5); insert(root, 2); insert(root, 7); insert(root, 12); insert(root, 9); insert(root, 15); Greater_BST(root); // print inorder traversal of the Greater BST inorder(root); return 0;}", "e": 45335, "s": 43204, "text": null }, { "code": "// Java code to add all greater values to// every node in a given BST import java.util.*; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); System.out.print(node.data + \" \"); inorderUtil(node.right); } // adding new node public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node void Greater_BST(Node root) { int sum = 0; Node node = root; Stack<Node> stack = new Stack<Node>(); while (!stack.isEmpty() || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.add(node); node = node.right; } node = stack.pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 8 / \\ 5 12 / \\ / \\ 2 7 9 15 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(7); tree.insert(12); tree.insert(9); tree.insert(15); tree.Greater_BST(tree.root); // print inorder traversal of the Greater BST tree.inorder(); }}", "e": 47893, "s": 45335, "text": null }, { "code": "# Python3 program to add all greater values# in every node of BST through Iteration using Stack # A utility function to create a# new BST nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative function to add all greater# values in every node def Greater_BST(root): total = 0 node = root stack = [] while stack or node is not None: # push all nodes up to (and including) # this subtree's maximum on # the stack. while node is not None: stack.append(node) node = node.right node = stack.pop() total += node.data node.data = total # all nodes with values between # the current and its parent lie in # the left subtree. node = node.left # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.data, end =\" \") inorder(root.right) # A utility function to insert a new node# with given data in BSTdef insert(node, data): # If the tree is empty, return a new node if node == None: return newNode(data) # Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 8 # / \\ # 5 12 # / \\ / \\ # 2 7 9 15 root = None root = insert(root, 8) insert(root, 5) insert(root, 2) insert(root, 7) insert(root, 9) insert(root, 12) insert(root, 15) Greater_BST(root) # print inorder traversal of the # Greater BST inorder(root) ", "e": 49768, "s": 47893, "text": null }, { "code": "// C# code to add all greater values to// every node in a given BSTusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); Console.Write(node.data + \" \"); inorderUtil(node.right); } // adding new node public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node void Greater_BST(Node root) { int sum = 0; Node node = root; Stack<Node> stack = new Stack<Node>(); while (stack.Count!=0 || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.Push(node); node = node.right; } node = stack.Pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 8 / \\ 5 12 / \\ / \\ 2 7 9 15 */ tree.insert(8); tree.insert(5); tree.insert(2); tree.insert(7); tree.insert(12); tree.insert(9); tree.insert(15); tree.Greater_BST(tree.root); // print inorder traversal of the Greater BST tree.inorder(); }} // This code is contributed by Rajput-Ji", "e": 52130, "s": 49768, "text": null }, { "code": "<script>// javascript code to add all greater values to// every node in a given BST// A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // Inorder traversal of the tree function inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of // the tree function inorderUtil(node) { if (node == null) return; inorderUtil(node.left); document.write(node.data + \" \"); inorderUtil(node.right); } // adding new node function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given data in BST */ function insertRec(node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data <= node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // Iterative function to add // all greater values in every node function Greater_BST(root) { var sum = 0; var node = root; var stack = []; while (stack.length!= 0 || node != null) { /* push all nodes up to (and including) this * subtree's maximum on the stack. */ while (node != null) { stack.push(node); node = node.right; } node = stack.pop(); sum += node.data; node.data = sum; /* all nodes with values between the current and * its parent lie in the left subtree. */ node = node.left; } } // Driver Function /* * Let us create following BST * 8 / \\ 5 12 / \\ / \\ 2 7 9 15 */ insert(8); insert(5); insert(2); insert(7); insert(12); insert(9); insert(15); Greater_BST(root); // print inorder traversal of the Greater BST inorder(); // This code is contributed by Rajput-Ji</script>", "e": 54479, "s": 52130, "text": null }, { "code": null, "e": 54487, "s": 54479, "text": "Output:" }, { "code": null, "e": 54509, "s": 54487, "text": "58 56 51 44 36 27 15 " }, { "code": null, "e": 54559, "s": 54509, "text": "Time Complexity: O(n) , n is no.of Node in a BST." }, { "code": null, "e": 54614, "s": 54559, "text": "Auxiliary Space: O(n). Stack is used for storing data." }, { "code": null, "e": 55493, "s": 54614, "text": "YouTubeGeeksforGeeks501K subscribersConvert a BST to a Binary Tree so that sum of greater keys is added to every key | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9zAPzXK5EaU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 55658, "s": 55493, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbkPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 55670, "s": 55658, "text": "shrikanth13" }, { "code": null, "e": 55686, "s": 55670, "text": "PranchalKatiyar" }, { "code": null, "e": 55701, "s": 55686, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 55713, "s": 55701, "text": "aksrathod07" }, { "code": null, "e": 55725, "s": 55713, "text": "anikakapoor" }, { "code": null, "e": 55732, "s": 55725, "text": "rrrtnx" }, { "code": null, "e": 55748, "s": 55732, "text": "saurabh1990aror" }, { "code": null, "e": 55758, "s": 55748, "text": "Rajput-Ji" }, { "code": null, "e": 55767, "s": 55758, "text": "sweetyty" }, { "code": null, "e": 55774, "s": 55767, "text": "Amazon" }, { "code": null, "e": 55778, "s": 55774, "text": "BST" }, { "code": null, "e": 55797, "s": 55778, "text": "Binary Search Tree" }, { "code": null, "e": 55804, "s": 55797, "text": "Amazon" }, { "code": null, "e": 55823, "s": 55804, "text": "Binary Search Tree" }, { "code": null, "e": 55921, "s": 55823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55953, "s": 55921, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 55993, "s": 55953, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 56028, "s": 55993, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 56085, "s": 56028, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 56155, "s": 56085, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 56189, "s": 56155, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 56237, "s": 56189, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 56291, "s": 56237, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 56351, "s": 56291, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
Data Science 101. A Step-by-Step Guide | Towards Data Science
IntroductionProblem StatementData CollectionExploratory Data AnalysisFeature EngineeringModel ComparisonResults DiscussionSummaryReferences Introduction Problem Statement Data Collection Exploratory Data Analysis Feature Engineering Model Comparison Results Discussion Summary References There is a certain trend in all technical processes, and data science is no exception. As you obtain more and more experience in any job, you start to notice a trend, which tends to make the job a little easier. The goal of this article is to make your data science job a little more streamlined because the process that I will outline below applies to every data science use case (or at least most), and for those that it is not 100% applicable for, it can still, hopefully, be useful to you. As you will see, there are six main steps to this process — mainly for the development parts of the model. It is not necessarily for deploying the model into a production environment. This process highlights steps from the problem you are trying to solve to the answer of that problem using data science techniques. Keep reading below, if you would like to know more about the six steps of the data science process. To build a data science model or utilize a machine learning algorithm, you will need to understand what the problem is. This step can also be called something more along the lines of a ‘business use case’. In this step, you will most likely experience working with stakeholders the most, anyone from data analysts, business analysts, product managers, to your company’s senior executives. Here is an example of a bad problem statement: “We wanna predict how many people will buy our product in the year 2022” Here is an example of a good problem statement: “The current way of predicting sales is inaccurate” While the first example makes sense, it does not highlight the problem, it highlighted a possible solution instead. The focus first should always be to understand the problem in its simplest form. From there, we can then present possible solutions using data science techniques and models. Another part of the problem statement can be the process of defining goals. For example, it will be useful to ask what the current sales prediction accuracy is, the goal accuracy, and hopefully, if the model can or cannot reach that goal accuracy, and what it means to not reach it exactly. Regarding the holistic data science process described in this article, the data collection process is perhaps the furthest removed step from academia to professional environments. As an example, in an educational course, you may be given a dataset right away that is already processed and explored. For working environments or professional settings, you will have to learn how to acquire that data from an outside source or an internal source within a data table. This step can take quite a bit of time as you will need to explore nearly all data tables in your database, or across databases. The data that you ultimately acquire might use different data from various sources. The final data will eventually be read into a dataframe so that it can then be analyzed, trained, and predicted on. Here are some possible ways of acquiring data: from Google Sheets from CSV files from Salesforce JSON files database tables from other websites and much more This step in the data science process can generally follow the same format. At this point, you will have your main, single dataframe. For the sake of the data science problem, you will need to separate your X features versus your y target variable — what you are trying to predict. These features can span from one to hundreds, or even more, but it is best to start off simple and analyze the main features of your dataset first (the ones you intuitively expect to be significant to the model’s prediction), and then get a glimpse of all of the features next. You can look at a variety of descriptive statistics that can help to define your data, here are some of the easier and more common ways to describe your data — oftentimes with the pandas library: df[[‘feature_1’, ‘feature_n’]].head() — first 5 rows of your data df[[‘feature_1’, ‘feature_n’]].tail() — last 5 rows of your data df[[‘feature_1’, ‘feature_n’]].describe() — count, mean, std, min, 25%, 50%, 75%, max — giving you a good idea of the distribution of your data and specific features analyzing missing data — sometimes it is expected data anomalies erroneous data — negative values that should not be negative, etc. If you want a big shortcut, you can use pandas profiling, which shows all of these descriptive statistics about your dataframe, and much more in just a few lines of code [5]: pandas-profiling.github.io Now that you have explored your data, you might want to engineer your features. To me, this step of the process should be called “before model feature engineering” — as in you are not using a model to edit your features. With that being said, there are a variety of ways that you expect to work with your features. Some of these include methods like creating new features by simply dividing two features together, to grouping features together for the creation of aggregate features. Here are some examples of feature engineering: addition/subtraction/division, etc. of current features to make new features grouping features to create aggregate features one hot encoding target encoding for categorical variables to reduce the dimensionality of your dataframe As you can see, we have performed several steps before starting to discuss the main ‘data science’ part. In this section, whether you are performing something like regression or classification, it is always best to compare several models before choosing one to update and enhance as your final model(s). For example, although it might seem obvious to pick a specific machine learning algorithm for your use case, it is best to remove your bias, and obtain a baseline for say, 5 to 10 common algorithms. From there, you can compare the benefits of each — not just the accuracy. For example, you might want to compare the time it takes to train the model, or how expensive it could be, to the requirements of transforming your data. Here are some common data science model comparison methods: hand-coding several algorithms and creating a table or dataframe that shows results of the benefits or disadvantages against one another-side-by-side PyCaret [8] I tend to compare models in the most baseline approach possible so that I do not get into the weeds too much with a particular algorithm, in case I end up not using it Before implementing your model into production, you will need to discuss the results with your stakeholder. You will look at what your accuracy means or your loss metric, like RMSE — Root Mean Square Error. These results are oftentimes confusing to people who do not study or employ data science, so it is your job to make them as simple as possible so that stakeholders can make decisions from your results — to move on or not for example (sometimes a complex machine learning algorithm is not the answer to the problem). Here are some things to keep in mind as you discuss your results: display results with a visual, in addition to the raw results — use tools like Tableau, Google Data Studio, or create your own in Python aggregate by certain features to highlight where the error is higher or lower, or accuracy is higher or lower explain what you would do with more data, more time, or a different algorithm explain what the results mean on the business and financial side of the company — does this model save money or does it just cost money to create and run? does your model make the process faster, does it make it better? does it help the internal users only or does it help the customers of your company's product? There is much to discuss when incorporating a data science model into a company’s ecosystem. That being said, the final step would be to automate the model by putting it into production. These main steps are important to most data science projects. The steps that happen after usually involve more machine learning operations — meaning, now that your model is approved, you can implement it into the product by involving software engineers, UX/UI researchers, more product managers, and statisticians for A/B tests. One important question you should ask now that the model makes sense to use, is how will you use it? does your model cause a negative or positive action from customers down the road— for example? As you can see, there are a lot of things to think about when incorporating data science at a company, but following these six main steps can set an easy outline and plan of attack for efficiently solving a problem using data science. To summarize, here are the six steps you can apply to every data science use case: * Problem Statement* Data Collection* Exploratory Data Analysis* Feature Engineering* Model Comparison* Results Discussion I hope you found my article both interesting and useful. Please feel free to comment down below if you follow this main process for data science implementation — do you agree or disagree, which steps would you remove or add? Do you think it will be beneficial if you do implement this process moving forward in the future? Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I am not affiliated with any of the mentioned companies. [1] Photo by Green Chameleon on Unsplash, (2015) [2] Photo by Emily Morter on Unsplash, (2017) [3] Photo by Tobias Fischer on Unsplash, (2017) [4] Photo by Firmbee.com on Unsplash, (2015) [5] Pandas Profiling — Simon Brigman, Pandas Profiling Homepage, (2021) [6] Photo by Jeswin Thomas on Unsplash, (2020) [7] Photo by Robert Anasch on Unsplash, (2018) [8] Moez Ali, PyCaret Homepage, (2021) [9] Photo by Ali Saadat on Unsplash, (2020)
[ { "code": null, "e": 312, "s": 172, "text": "IntroductionProblem StatementData CollectionExploratory Data AnalysisFeature EngineeringModel ComparisonResults DiscussionSummaryReferences" }, { "code": null, "e": 325, "s": 312, "text": "Introduction" }, { "code": null, "e": 343, "s": 325, "text": "Problem Statement" }, { "code": null, "e": 359, "s": 343, "text": "Data Collection" }, { "code": null, "e": 385, "s": 359, "text": "Exploratory Data Analysis" }, { "code": null, "e": 405, "s": 385, "text": "Feature Engineering" }, { "code": null, "e": 422, "s": 405, "text": "Model Comparison" }, { "code": null, "e": 441, "s": 422, "text": "Results Discussion" }, { "code": null, "e": 449, "s": 441, "text": "Summary" }, { "code": null, "e": 460, "s": 449, "text": "References" }, { "code": null, "e": 1370, "s": 460, "text": "There is a certain trend in all technical processes, and data science is no exception. As you obtain more and more experience in any job, you start to notice a trend, which tends to make the job a little easier. The goal of this article is to make your data science job a little more streamlined because the process that I will outline below applies to every data science use case (or at least most), and for those that it is not 100% applicable for, it can still, hopefully, be useful to you. As you will see, there are six main steps to this process — mainly for the development parts of the model. It is not necessarily for deploying the model into a production environment. This process highlights steps from the problem you are trying to solve to the answer of that problem using data science techniques. Keep reading below, if you would like to know more about the six steps of the data science process." }, { "code": null, "e": 1759, "s": 1370, "text": "To build a data science model or utilize a machine learning algorithm, you will need to understand what the problem is. This step can also be called something more along the lines of a ‘business use case’. In this step, you will most likely experience working with stakeholders the most, anyone from data analysts, business analysts, product managers, to your company’s senior executives." }, { "code": null, "e": 1806, "s": 1759, "text": "Here is an example of a bad problem statement:" }, { "code": null, "e": 1879, "s": 1806, "text": "“We wanna predict how many people will buy our product in the year 2022”" }, { "code": null, "e": 1927, "s": 1879, "text": "Here is an example of a good problem statement:" }, { "code": null, "e": 1979, "s": 1927, "text": "“The current way of predicting sales is inaccurate”" }, { "code": null, "e": 2269, "s": 1979, "text": "While the first example makes sense, it does not highlight the problem, it highlighted a possible solution instead. The focus first should always be to understand the problem in its simplest form. From there, we can then present possible solutions using data science techniques and models." }, { "code": null, "e": 2560, "s": 2269, "text": "Another part of the problem statement can be the process of defining goals. For example, it will be useful to ask what the current sales prediction accuracy is, the goal accuracy, and hopefully, if the model can or cannot reach that goal accuracy, and what it means to not reach it exactly." }, { "code": null, "e": 3353, "s": 2560, "text": "Regarding the holistic data science process described in this article, the data collection process is perhaps the furthest removed step from academia to professional environments. As an example, in an educational course, you may be given a dataset right away that is already processed and explored. For working environments or professional settings, you will have to learn how to acquire that data from an outside source or an internal source within a data table. This step can take quite a bit of time as you will need to explore nearly all data tables in your database, or across databases. The data that you ultimately acquire might use different data from various sources. The final data will eventually be read into a dataframe so that it can then be analyzed, trained, and predicted on." }, { "code": null, "e": 3400, "s": 3353, "text": "Here are some possible ways of acquiring data:" }, { "code": null, "e": 3419, "s": 3400, "text": "from Google Sheets" }, { "code": null, "e": 3434, "s": 3419, "text": "from CSV files" }, { "code": null, "e": 3450, "s": 3434, "text": "from Salesforce" }, { "code": null, "e": 3461, "s": 3450, "text": "JSON files" }, { "code": null, "e": 3477, "s": 3461, "text": "database tables" }, { "code": null, "e": 3497, "s": 3477, "text": "from other websites" }, { "code": null, "e": 3511, "s": 3497, "text": "and much more" }, { "code": null, "e": 4071, "s": 3511, "text": "This step in the data science process can generally follow the same format. At this point, you will have your main, single dataframe. For the sake of the data science problem, you will need to separate your X features versus your y target variable — what you are trying to predict. These features can span from one to hundreds, or even more, but it is best to start off simple and analyze the main features of your dataset first (the ones you intuitively expect to be significant to the model’s prediction), and then get a glimpse of all of the features next." }, { "code": null, "e": 4267, "s": 4071, "text": "You can look at a variety of descriptive statistics that can help to define your data, here are some of the easier and more common ways to describe your data — oftentimes with the pandas library:" }, { "code": null, "e": 4333, "s": 4267, "text": "df[[‘feature_1’, ‘feature_n’]].head() — first 5 rows of your data" }, { "code": null, "e": 4398, "s": 4333, "text": "df[[‘feature_1’, ‘feature_n’]].tail() — last 5 rows of your data" }, { "code": null, "e": 4564, "s": 4398, "text": "df[[‘feature_1’, ‘feature_n’]].describe() — count, mean, std, min, 25%, 50%, 75%, max — giving you a good idea of the distribution of your data and specific features" }, { "code": null, "e": 4614, "s": 4564, "text": "analyzing missing data — sometimes it is expected" }, { "code": null, "e": 4629, "s": 4614, "text": "data anomalies" }, { "code": null, "e": 4696, "s": 4629, "text": "erroneous data — negative values that should not be negative, etc." }, { "code": null, "e": 4871, "s": 4696, "text": "If you want a big shortcut, you can use pandas profiling, which shows all of these descriptive statistics about your dataframe, and much more in just a few lines of code [5]:" }, { "code": null, "e": 4898, "s": 4871, "text": "pandas-profiling.github.io" }, { "code": null, "e": 5382, "s": 4898, "text": "Now that you have explored your data, you might want to engineer your features. To me, this step of the process should be called “before model feature engineering” — as in you are not using a model to edit your features. With that being said, there are a variety of ways that you expect to work with your features. Some of these include methods like creating new features by simply dividing two features together, to grouping features together for the creation of aggregate features." }, { "code": null, "e": 5429, "s": 5382, "text": "Here are some examples of feature engineering:" }, { "code": null, "e": 5506, "s": 5429, "text": "addition/subtraction/division, etc. of current features to make new features" }, { "code": null, "e": 5553, "s": 5506, "text": "grouping features to create aggregate features" }, { "code": null, "e": 5570, "s": 5553, "text": "one hot encoding" }, { "code": null, "e": 5659, "s": 5570, "text": "target encoding for categorical variables to reduce the dimensionality of your dataframe" }, { "code": null, "e": 5963, "s": 5659, "text": "As you can see, we have performed several steps before starting to discuss the main ‘data science’ part. In this section, whether you are performing something like regression or classification, it is always best to compare several models before choosing one to update and enhance as your final model(s)." }, { "code": null, "e": 6390, "s": 5963, "text": "For example, although it might seem obvious to pick a specific machine learning algorithm for your use case, it is best to remove your bias, and obtain a baseline for say, 5 to 10 common algorithms. From there, you can compare the benefits of each — not just the accuracy. For example, you might want to compare the time it takes to train the model, or how expensive it could be, to the requirements of transforming your data." }, { "code": null, "e": 6450, "s": 6390, "text": "Here are some common data science model comparison methods:" }, { "code": null, "e": 6600, "s": 6450, "text": "hand-coding several algorithms and creating a table or dataframe that shows results of the benefits or disadvantages against one another-side-by-side" }, { "code": null, "e": 6612, "s": 6600, "text": "PyCaret [8]" }, { "code": null, "e": 6780, "s": 6612, "text": "I tend to compare models in the most baseline approach possible so that I do not get into the weeds too much with a particular algorithm, in case I end up not using it" }, { "code": null, "e": 7303, "s": 6780, "text": "Before implementing your model into production, you will need to discuss the results with your stakeholder. You will look at what your accuracy means or your loss metric, like RMSE — Root Mean Square Error. These results are oftentimes confusing to people who do not study or employ data science, so it is your job to make them as simple as possible so that stakeholders can make decisions from your results — to move on or not for example (sometimes a complex machine learning algorithm is not the answer to the problem)." }, { "code": null, "e": 7369, "s": 7303, "text": "Here are some things to keep in mind as you discuss your results:" }, { "code": null, "e": 7506, "s": 7369, "text": "display results with a visual, in addition to the raw results — use tools like Tableau, Google Data Studio, or create your own in Python" }, { "code": null, "e": 7616, "s": 7506, "text": "aggregate by certain features to highlight where the error is higher or lower, or accuracy is higher or lower" }, { "code": null, "e": 7694, "s": 7616, "text": "explain what you would do with more data, more time, or a different algorithm" }, { "code": null, "e": 7849, "s": 7694, "text": "explain what the results mean on the business and financial side of the company — does this model save money or does it just cost money to create and run?" }, { "code": null, "e": 7914, "s": 7849, "text": "does your model make the process faster, does it make it better?" }, { "code": null, "e": 8008, "s": 7914, "text": "does it help the internal users only or does it help the customers of your company's product?" }, { "code": null, "e": 8195, "s": 8008, "text": "There is much to discuss when incorporating a data science model into a company’s ecosystem. That being said, the final step would be to automate the model by putting it into production." }, { "code": null, "e": 8625, "s": 8195, "text": "These main steps are important to most data science projects. The steps that happen after usually involve more machine learning operations — meaning, now that your model is approved, you can implement it into the product by involving software engineers, UX/UI researchers, more product managers, and statisticians for A/B tests. One important question you should ask now that the model makes sense to use, is how will you use it?" }, { "code": null, "e": 8720, "s": 8625, "text": "does your model cause a negative or positive action from customers down the road— for example?" }, { "code": null, "e": 8955, "s": 8720, "text": "As you can see, there are a lot of things to think about when incorporating data science at a company, but following these six main steps can set an easy outline and plan of attack for efficiently solving a problem using data science." }, { "code": null, "e": 9038, "s": 8955, "text": "To summarize, here are the six steps you can apply to every data science use case:" }, { "code": null, "e": 9161, "s": 9038, "text": "* Problem Statement* Data Collection* Exploratory Data Analysis* Feature Engineering* Model Comparison* Results Discussion" }, { "code": null, "e": 9484, "s": 9161, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you follow this main process for data science implementation — do you agree or disagree, which steps would you remove or add? Do you think it will be beneficial if you do implement this process moving forward in the future?" }, { "code": null, "e": 9642, "s": 9484, "text": "Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn. I am not affiliated with any of the mentioned companies." }, { "code": null, "e": 9691, "s": 9642, "text": "[1] Photo by Green Chameleon on Unsplash, (2015)" }, { "code": null, "e": 9737, "s": 9691, "text": "[2] Photo by Emily Morter on Unsplash, (2017)" }, { "code": null, "e": 9785, "s": 9737, "text": "[3] Photo by Tobias Fischer on Unsplash, (2017)" }, { "code": null, "e": 9830, "s": 9785, "text": "[4] Photo by Firmbee.com on Unsplash, (2015)" }, { "code": null, "e": 9902, "s": 9830, "text": "[5] Pandas Profiling — Simon Brigman, Pandas Profiling Homepage, (2021)" }, { "code": null, "e": 9949, "s": 9902, "text": "[6] Photo by Jeswin Thomas on Unsplash, (2020)" }, { "code": null, "e": 9996, "s": 9949, "text": "[7] Photo by Robert Anasch on Unsplash, (2018)" }, { "code": null, "e": 10035, "s": 9996, "text": "[8] Moez Ali, PyCaret Homepage, (2021)" } ]
Write a Golang program to reverse an array
Input arr = [3, 5, 7, 9, 10, 4] => [4, 10, 9, 7, 5, 3] Input arr = [1, 2, 3, 4, 5] => [5, 4, 3, 2, 1] Step 1: Define a function that accepts an array. Step 2: Start iterating the input array. Step 3: Swap first element with last element of the given array. Step 4: Return array. Live Demo package main import "fmt" func reverseArray(arr []int) []int{ for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 { arr[i], arr[j] = arr[j], arr[i] } return arr } func main(){ fmt.Println(reverseArray([]int{1, 2, 3, 4, 5})) fmt.Println(reverseArray([]int{3, 5, 7, 2, 1})) fmt.Println(reverseArray([]int{9, 8, 6, 1, 0})) } [5 4 3 2 1] [1 2 7 5 3] [0 1 6 8 9]
[ { "code": null, "e": 1117, "s": 1062, "text": "Input arr = [3, 5, 7, 9, 10, 4] => [4, 10, 9, 7, 5, 3]" }, { "code": null, "e": 1164, "s": 1117, "text": "Input arr = [1, 2, 3, 4, 5] => [5, 4, 3, 2, 1]" }, { "code": null, "e": 1213, "s": 1164, "text": "Step 1: Define a function that accepts an array." }, { "code": null, "e": 1254, "s": 1213, "text": "Step 2: Start iterating the input array." }, { "code": null, "e": 1319, "s": 1254, "text": "Step 3: Swap first element with last element of the given array." }, { "code": null, "e": 1341, "s": 1319, "text": "Step 4: Return array." }, { "code": null, "e": 1351, "s": 1341, "text": "Live Demo" }, { "code": null, "e": 1695, "s": 1351, "text": "package main\nimport \"fmt\"\n\nfunc reverseArray(arr []int) []int{\n for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 {\n arr[i], arr[j] = arr[j], arr[i]\n }\n return arr\n}\n\nfunc main(){\n fmt.Println(reverseArray([]int{1, 2, 3, 4, 5}))\n fmt.Println(reverseArray([]int{3, 5, 7, 2, 1}))\n fmt.Println(reverseArray([]int{9, 8, 6, 1, 0}))\n}" }, { "code": null, "e": 1731, "s": 1695, "text": "[5 4 3 2 1]\n[1 2 7 5 3]\n[0 1 6 8 9]" } ]
Perl | Loops (for, foreach, while, do...while, until, Nested loops) - GeeksforGeeks
16 Jun, 2021 Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop “for” loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax: for (init statement; condition; increment/decrement ) { # Code to be Executed } Flow Chart: A for loop works on a predefined flow of control. The flow of control can be determined by the following : init statement: This is the first statement which is executed. In this step, we initialize a variable which controls the loop. condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed. increment/decrement: The loop control variable is changed here (incremented or decremented) for updating the variable for next iteration. Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle. Example : Perl # Perl program to illustrate# the for loop # for loopfor ($count = 1 ; $count <= 3 ; $count++){ print "GeeksForGeeks\n"} Output: GeeksForGeeks GeeksForGeeks GeeksForGeeks foreach Loop A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range. The process of iteration of each element is done automatically by the loop.Syntax: foreach variable { # Code to be Executed } Flow Chart: Example: Perl # Perl program to illustrate# the foreach loop # Array@data = ('GEEKS', 'FOR', 'GEEKS'); # foreach loopforeach $word (@data){ print $word} Output: GEEKSFORGEEKS while Loop A while loop generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as a entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement.Syntax : while (condition) { # Code to be executed } Flow Chart: Example : Perl # Perl program to illustrate# the while loop # while loop$count = 3;while ($count >= 0){ $count = $count - 1; print "GeeksForGeeks\n";} Output: GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks Infinite While Loop: While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions which always remain true, which causes while loop to execute infinite times or we can say it never terminates. Example: Below program will print the specified statement infinite time and also give the runtime error as Output Limit Exceeded on online IDE Perl # Perl program to illustrate# the infinite while loop # infinite while loop# containing condition 1# which is always truewhile(1){ print "Infinite While Loop\n";} Output: Infinite While Loop Infinite While Loop Infinite While Loop Infinite While Loop . . . . do.... while loop A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as exit controlled loop as the condition is checked after executing the loop.Syntax: do { # statements to be Executed } while(condition); Flow Chart: Example : Perl # Perl program to illustrate# do..while Loop $a = 10; # do..While loopdo { print "$a "; $a = $a - 1;} while ($a > 0); Output: 10 9 8 7 6 5 4 3 2 1 until loop until loop is the opposite of while loop. It takes a condition in the parenthesis and it only runs until the condition is false. Basically, it repeats an instruction or set of instruction until the condition is FALSE. It is also entry controller loop i.e. first the condition is checked then set of instructions inside a block is executed.Syntax: until (condition) { # Statements to be executed } Flow Chart: Example : Perl # Perl program to illustrate until Loop $a = 10; # until loopuntil ($a < 1){ print "$a "; $a = $a - 1;} Output: 10 9 8 7 6 5 4 3 2 1 Nested Loops A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming. And all above-discussed loops can be nested.Syntax for different nested loops in Perl: Nested for loop for (init statement; condition; increment/decrement ) { for (init statement; condition; increment/decrement ) { # Code to be Executed } } Nested foreach loop foreach variable_1 (@array_1) { foreach variable_2 (@array_2) { # Code to be Executed } } Nested while loop while (condition) { while (condition) { # Code to be Executed } } Nested do..while loop do{ do{ # Code to be Executed }while(condition); }while(condition); Nested until loop until (condition) { until (condition) { # Code to be Executed } } Example : Perl # Perl program to illustrate# nested while Loop $a = 5;$b = 0; # outer while loopwhile ($a < 7){ $b = 0; # inner while loop while ( $b <7 ) { print "value of a = $a, b = $b\n"; $b = $b + 1; } $a = $a + 1; print "Value of a = $a\n\n";} Output: value of a = 5, b = 0 value of a = 5, b = 1 value of a = 5, b = 2 value of a = 5, b = 3 value of a = 5, b = 4 value of a = 5, b = 5 value of a = 5, b = 6 Value of a = 6 value of a = 6, b = 0 value of a = 6, b = 1 value of a = 6, b = 2 value of a = 6, b = 3 value of a = 6, b = 4 value of a = 6, b = 5 value of a = 6, b = 6 Value of a = 7 varshagumber28 perl-basics Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | grep() Function Perl | exists() Function Perl | Removing leading and trailing white spaces (trim) Perl | substr() function Perl | length() Function Perl | sleep() Function Perl Tutorial - Learn Perl With Examples
[ { "code": null, "e": 25280, "s": 25252, "text": "\n16 Jun, 2021" }, { "code": null, "e": 25611, "s": 25280, "text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : " }, { "code": null, "e": 25622, "s": 25613, "text": "for Loop" }, { "code": null, "e": 25872, "s": 25622, "text": "“for” loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax: " }, { "code": null, "e": 25957, "s": 25872, "text": "for (init statement; condition; increment/decrement ) \n{\n # Code to be Executed\n}" }, { "code": null, "e": 25970, "s": 25957, "text": "Flow Chart: " }, { "code": null, "e": 26078, "s": 25970, "text": "A for loop works on a predefined flow of control. The flow of control can be determined by the following : " }, { "code": null, "e": 26205, "s": 26078, "text": "init statement: This is the first statement which is executed. In this step, we initialize a variable which controls the loop." }, { "code": null, "e": 26408, "s": 26205, "text": "condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements." }, { "code": null, "e": 26516, "s": 26408, "text": "Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed." }, { "code": null, "e": 26654, "s": 26516, "text": "increment/decrement: The loop control variable is changed here (incremented or decremented) for updating the variable for next iteration." }, { "code": null, "e": 26761, "s": 26654, "text": "Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle." }, { "code": null, "e": 26773, "s": 26761, "text": "Example : " }, { "code": null, "e": 26778, "s": 26773, "text": "Perl" }, { "code": "# Perl program to illustrate# the for loop # for loopfor ($count = 1 ; $count <= 3 ; $count++){ print \"GeeksForGeeks\\n\"}", "e": 26902, "s": 26778, "text": null }, { "code": null, "e": 26912, "s": 26902, "text": "Output: " }, { "code": null, "e": 26954, "s": 26912, "text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks" }, { "code": null, "e": 26969, "s": 26956, "text": "foreach Loop" }, { "code": null, "e": 27322, "s": 26969, "text": "A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range. The process of iteration of each element is done automatically by the loop.Syntax: " }, { "code": null, "e": 27370, "s": 27322, "text": "foreach variable \n{\n # Code to be Executed\n}" }, { "code": null, "e": 27383, "s": 27370, "text": "Flow Chart: " }, { "code": null, "e": 27393, "s": 27383, "text": "Example: " }, { "code": null, "e": 27398, "s": 27393, "text": "Perl" }, { "code": "# Perl program to illustrate# the foreach loop # Array@data = ('GEEKS', 'FOR', 'GEEKS'); # foreach loopforeach $word (@data){ print $word}", "e": 27540, "s": 27398, "text": null }, { "code": null, "e": 27550, "s": 27540, "text": "Output: " }, { "code": null, "e": 27564, "s": 27550, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 27577, "s": 27566, "text": "while Loop" }, { "code": null, "e": 28036, "s": 27577, "text": "A while loop generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as a entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement.Syntax : " }, { "code": null, "e": 28084, "s": 28036, "text": "while (condition)\n{\n # Code to be executed\n}" }, { "code": null, "e": 28097, "s": 28084, "text": "Flow Chart: " }, { "code": null, "e": 28109, "s": 28097, "text": "Example : " }, { "code": null, "e": 28114, "s": 28109, "text": "Perl" }, { "code": "# Perl program to illustrate# the while loop # while loop$count = 3;while ($count >= 0){ $count = $count - 1; print \"GeeksForGeeks\\n\";}", "e": 28256, "s": 28114, "text": null }, { "code": null, "e": 28266, "s": 28256, "text": "Output: " }, { "code": null, "e": 28322, "s": 28266, "text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks" }, { "code": null, "e": 28608, "s": 28322, "text": "Infinite While Loop: While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions which always remain true, which causes while loop to execute infinite times or we can say it never terminates. " }, { "code": null, "e": 28752, "s": 28608, "text": "Example: Below program will print the specified statement infinite time and also give the runtime error as Output Limit Exceeded on online IDE " }, { "code": null, "e": 28757, "s": 28752, "text": "Perl" }, { "code": "# Perl program to illustrate# the infinite while loop # infinite while loop# containing condition 1# which is always truewhile(1){ print \"Infinite While Loop\\n\";}", "e": 28923, "s": 28757, "text": null }, { "code": null, "e": 28933, "s": 28923, "text": "Output: " }, { "code": null, "e": 29021, "s": 28933, "text": "Infinite While Loop\nInfinite While Loop\nInfinite While Loop\nInfinite While Loop\n.\n.\n.\n." }, { "code": null, "e": 29041, "s": 29023, "text": "do.... while loop" }, { "code": null, "e": 29386, "s": 29041, "text": "A do..while loop is almost same as a while loop. The only difference is that do..while loop runs at least one time. The condition is checked after the first execution. A do..while loop is used when we want the loop to run at least one time. It is also known as exit controlled loop as the condition is checked after executing the loop.Syntax: " }, { "code": null, "e": 29445, "s": 29386, "text": "do {\n\n # statements to be Executed\n\n} while(condition);" }, { "code": null, "e": 29459, "s": 29445, "text": "Flow Chart: " }, { "code": null, "e": 29471, "s": 29459, "text": "Example : " }, { "code": null, "e": 29476, "s": 29471, "text": "Perl" }, { "code": "# Perl program to illustrate# do..while Loop $a = 10; # do..While loopdo { print \"$a \"; $a = $a - 1;} while ($a > 0);", "e": 29601, "s": 29476, "text": null }, { "code": null, "e": 29611, "s": 29601, "text": "Output: " }, { "code": null, "e": 29632, "s": 29611, "text": "10 9 8 7 6 5 4 3 2 1" }, { "code": null, "e": 29645, "s": 29634, "text": "until loop" }, { "code": null, "e": 29993, "s": 29645, "text": "until loop is the opposite of while loop. It takes a condition in the parenthesis and it only runs until the condition is false. Basically, it repeats an instruction or set of instruction until the condition is FALSE. It is also entry controller loop i.e. first the condition is checked then set of instructions inside a block is executed.Syntax: " }, { "code": null, "e": 30047, "s": 29993, "text": "until (condition) \n{\n # Statements to be executed\n}" }, { "code": null, "e": 30060, "s": 30047, "text": "Flow Chart: " }, { "code": null, "e": 30072, "s": 30060, "text": "Example : " }, { "code": null, "e": 30077, "s": 30072, "text": "Perl" }, { "code": "# Perl program to illustrate until Loop $a = 10; # until loopuntil ($a < 1){ print \"$a \"; $a = $a - 1;}", "e": 30187, "s": 30077, "text": null }, { "code": null, "e": 30197, "s": 30187, "text": "Output: " }, { "code": null, "e": 30218, "s": 30197, "text": "10 9 8 7 6 5 4 3 2 1" }, { "code": null, "e": 30233, "s": 30220, "text": "Nested Loops" }, { "code": null, "e": 30413, "s": 30233, "text": "A nested loop is a loop inside a loop. Nested loops are also supported by Perl Programming. And all above-discussed loops can be nested.Syntax for different nested loops in Perl: " }, { "code": null, "e": 30431, "s": 30413, "text": "Nested for loop " }, { "code": null, "e": 30592, "s": 30431, "text": "for (init statement; condition; increment/decrement ) \n{\n for (init statement; condition; increment/decrement ) \n {\n # Code to be Executed\n }\n}" }, { "code": null, "e": 30616, "s": 30594, "text": "Nested foreach loop " }, { "code": null, "e": 30727, "s": 30616, "text": "foreach variable_1 (@array_1) {\n\n foreach variable_2 (@array_2) \n {\n\n # Code to be Executed\n } \n}" }, { "code": null, "e": 30749, "s": 30729, "text": "Nested while loop " }, { "code": null, "e": 30835, "s": 30749, "text": "while (condition)\n{\n while (condition)\n {\n # Code to be Executed\n }\n}" }, { "code": null, "e": 30861, "s": 30837, "text": "Nested do..while loop " }, { "code": null, "e": 30951, "s": 30861, "text": "do{\n do{\n\n # Code to be Executed\n\n }while(condition);\n\n}while(condition);" }, { "code": null, "e": 30971, "s": 30951, "text": "Nested until loop " }, { "code": null, "e": 31058, "s": 30971, "text": "until (condition) {\n\n until (condition) \n {\n # Code to be Executed\n }\n}" }, { "code": null, "e": 31072, "s": 31060, "text": "Example : " }, { "code": null, "e": 31077, "s": 31072, "text": "Perl" }, { "code": "# Perl program to illustrate# nested while Loop $a = 5;$b = 0; # outer while loopwhile ($a < 7){ $b = 0; # inner while loop while ( $b <7 ) { print \"value of a = $a, b = $b\\n\"; $b = $b + 1; } $a = $a + 1; print \"Value of a = $a\\n\\n\";}", "e": 31344, "s": 31077, "text": null }, { "code": null, "e": 31354, "s": 31344, "text": "Output: " }, { "code": null, "e": 31693, "s": 31354, "text": "value of a = 5, b = 0\nvalue of a = 5, b = 1\nvalue of a = 5, b = 2\nvalue of a = 5, b = 3\nvalue of a = 5, b = 4\nvalue of a = 5, b = 5\nvalue of a = 5, b = 6\nValue of a = 6\n\nvalue of a = 6, b = 0\nvalue of a = 6, b = 1\nvalue of a = 6, b = 2\nvalue of a = 6, b = 3\nvalue of a = 6, b = 4\nvalue of a = 6, b = 5\nvalue of a = 6, b = 6\nValue of a = 7" }, { "code": null, "e": 31710, "s": 31695, "text": "varshagumber28" }, { "code": null, "e": 31722, "s": 31710, "text": "perl-basics" }, { "code": null, "e": 31727, "s": 31722, "text": "Perl" }, { "code": null, "e": 31732, "s": 31727, "text": "Perl" }, { "code": null, "e": 31830, "s": 31732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31839, "s": 31830, "text": "Comments" }, { "code": null, "e": 31852, "s": 31839, "text": "Old Comments" }, { "code": null, "e": 31876, "s": 31852, "text": "Perl | split() Function" }, { "code": null, "e": 31899, "s": 31876, "text": "Perl | push() Function" }, { "code": null, "e": 31923, "s": 31899, "text": "Perl | chomp() Function" }, { "code": null, "e": 31946, "s": 31923, "text": "Perl | grep() Function" }, { "code": null, "e": 31971, "s": 31946, "text": "Perl | exists() Function" }, { "code": null, "e": 32028, "s": 31971, "text": "Perl | Removing leading and trailing white spaces (trim)" }, { "code": null, "e": 32053, "s": 32028, "text": "Perl | substr() function" }, { "code": null, "e": 32078, "s": 32053, "text": "Perl | length() Function" }, { "code": null, "e": 32102, "s": 32078, "text": "Perl | sleep() Function" } ]
Using Open Source Prophet Package to Make Future Predictions in R | by Harel Rechavia | Towards Data Science
Almost every company wishes to answer where they will be one week/month/year from now.The answers to those questions can be valuable when planning the company’s infrastructure, KPIs (key performance indicators) and worker goals.Hence, using data forecasting tools are one of the common tasks data professionals are being asked to take on. One tool which was recently released as an open source is Facebook’s time series forecasting package Prophet. Available both for R and Python, this is a relatively easy to implement model with some much needed customization options. In this post I’ll review Prophet and follow it by a simple R code example. This code flow is heavily inspired from the official package users guide. We will use an open data set extracted from wikishark holding daily data entrances to LeBron James Wikipedia article page. Next, we will build daily predictions based on historical data.* wikishark was closed after the release of the article. you can use another useful site to get the data. install.packages(‘prophet’)library(prophet)library(dplyr) stats <- read.csv(“lebron.csv”, header=FALSE, sep=”,”)colnames(stats) <- c(“ds”, “y”)head(stats)#daily data points starting from 2014–01–0 stats$y <- log10(stats$y) For our code example we will transform the data and use the log of entrances. This will help us make sense of the prediction visualizations. View(summary(stats))plot(y ~ ds, stats, type = "l") We can see the data is from 2014–01–01 and up to 2016–12–31 with some yearly seasonality peaks from April thorough June. m <- prophet(stats)future <- make_future_dataframe(m, periods = 365)forecast <- predict(m, future) Like machine learning models the first command fits a model on the dataframe and next will deploy the model using the predict command in order to receive predictions for the length of days required. plot(m, forecast) The out of the box visualizations of the prophet package are quite nice with predefined tick marks, data points and uncertainty intervals. This is one of the advantages of this open source package, no need for extra customization and the first result is fast and good enough for most needs. Using this graph we spot the yearly trend and seasonality much clearer and how these are used for making predictions. tail(forecast[c(‘ds’, ‘yhat’, ‘yhat_lower’, ‘yhat_upper’)]) The forecast object holds the raw data with the predicted value by day and uncertainty intervals. It is also possible to access the prediction trends and seasonality components with: tail(forecast) prophet_plot_components(m, forecast) keeping up with the simplicity, its easy to look into the components of the model. Showing the overall trend, weekly and yearly seasonality. The last components graph has shown the raising interest with LeBron James during the NBA playoffs and during the NBA finals. The model at this point recognizes the yearly seasonality which returns every year. On a side note, LeBron James currently holds the record for 6 consecutive years of playing the NBA playoffs starting with Miami and continuing with the Cavaliers. So we should expect the same seasonality year after year. Adding holidays and events is a major advantage of the package. Firstly by making the predictions more accurate and allowing the user to take into considerations known future events. The developers had made this customization much easier than prior time series packages in which events and holidays should have been manually changed or ignored in order to make predictions. Think of an e-commerce website that can add all reoccurring campaigns and promotions and set revenue goals based on known future campaign dates. Adding events and holidays is done by creating a new dataframe in which we pass the dates of begging or ending of the events and the length of the days. In this example we will add the NBA playoffs and NBA finals as events playoff_brackets <- data_frame( holiday = ‘playoffs’, ds = as.Date(c(‘2017–04–16’ ,’2016–04–17', ‘2015–04–19’, ‘2014–04–19’)), lower_window = 0, upper_window = 45)playoff_finals <- data_frame( holiday = ‘playoff_finals’, ds = as.Date(c(‘2016–06–02’, ‘2015–06–04’, ‘2014–06–05’)), lower_window = 0, upper_window = 20) Using the lower and upper window parameters the user can set the length of the holiday. Those mappings will be row binded to a single object and passed in holidays parameter. holidays <- bind_rows(playoff_brackets, playoff_finals)m <- prophet(stats, holidays = playoff_brackets)forecast <- predict(m, future)plot(m, forecast) Notice the model better predicts the values during the peaks. Printing out he components again will show the added row of holidays effect on prediction. Theoretically you can map many events which are critical for the business and get better predictions. When building predictions it is important to remove outliers from the historical data. The data points are used by the model which adds their effect to the predictions although they are single time events or just false event logs. Unlike other packages that will breakdown when passed an NA value with the historical data, Prophet will ignore those dates. In this example we will remove a series of single time event in which the NBA player announced he is leaving Miami in favor of Cleveland which probably draw attention to his Wikipedia page. outliers <- (as.Date(stats$ds) > as.Date(‘2014–07–09’) & as.Date(stats$ds) < as.Date(‘2014–07–12’))stats$y[outliers] = NA At this point we can see the simplicity and robust the developers had in mind when creating this package. Some extra functionality I didn’t show but should be used: Changing seasonality and holidays effect scale Mapping critical trend change points Editing uncertainty Intervals The next step I hope the developers will take is using this package and leverage it for anomaly detection for time series data. Prior packages offer such functionality but depend heavily on the data structure and strict seasonality. Lets use the existing model in order to map anomalies in the data. We will compare the original values (y) with the predicted model values (yhat) and create a new column called diff_values. combined_data <- cbind(head(forecast, nrow(stats)), stats[order(stats$ds),])combined_data$diff_values <- (combined_data$y - combined_data$yhat)summary(combined_data$diff_values)Min. 1st Qu. Median Mean 3rd Qu. Max. 0.05269 0.07326 0.10780 0.13490 0.16520 0.29480 To better generalize the detection of anomalies we will also add the normalized diff values representing the percent difference from actual values. combined_data$diff_values_normalized <-(combined_data$y - combined_data$yhat) / combined_data$y Lets go ahead and visualize the normalized diff values over time. plot(diff_values_normalized ~ ds, combined_data, type = “l”) Most predictions are quite close to the actual values as the graph tends to move around the 0 value. We can also ask what percent of data points are anomalies by filtering the absolute of the column diff_values_normalized. Setting a threshold from which a data point is considered a anomaly is one way to look at it. In this example its 10% nrow(combined_data[abs(combined_data$diff_values_normalized) > 0.1& !is.na(combined_data$y),]) / nrow(combined_data) We receive 0.02 which indicates that 2% of data points are anomalies based on the given threshold. Making predictions is an important skill for data professionals. Thanks for open sourced projects like Prophet this does not need to be too difficult. This package balances between simplicity, computation speed and the right amount of customization so both beginners and advanced users can use it. Thanks for reading,Harel Rechavia,Data Analyst at Viber
[ { "code": null, "e": 511, "s": 172, "text": "Almost every company wishes to answer where they will be one week/month/year from now.The answers to those questions can be valuable when planning the company’s infrastructure, KPIs (key performance indicators) and worker goals.Hence, using data forecasting tools are one of the common tasks data professionals are being asked to take on." }, { "code": null, "e": 893, "s": 511, "text": "One tool which was recently released as an open source is Facebook’s time series forecasting package Prophet. Available both for R and Python, this is a relatively easy to implement model with some much needed customization options. In this post I’ll review Prophet and follow it by a simple R code example. This code flow is heavily inspired from the official package users guide." }, { "code": null, "e": 1185, "s": 893, "text": "We will use an open data set extracted from wikishark holding daily data entrances to LeBron James Wikipedia article page. Next, we will build daily predictions based on historical data.* wikishark was closed after the release of the article. you can use another useful site to get the data." }, { "code": null, "e": 1243, "s": 1185, "text": "install.packages(‘prophet’)library(prophet)library(dplyr)" }, { "code": null, "e": 1382, "s": 1243, "text": "stats <- read.csv(“lebron.csv”, header=FALSE, sep=”,”)colnames(stats) <- c(“ds”, “y”)head(stats)#daily data points starting from 2014–01–0" }, { "code": null, "e": 1408, "s": 1382, "text": "stats$y <- log10(stats$y)" }, { "code": null, "e": 1549, "s": 1408, "text": "For our code example we will transform the data and use the log of entrances. This will help us make sense of the prediction visualizations." }, { "code": null, "e": 1601, "s": 1549, "text": "View(summary(stats))plot(y ~ ds, stats, type = \"l\")" }, { "code": null, "e": 1722, "s": 1601, "text": "We can see the data is from 2014–01–01 and up to 2016–12–31 with some yearly seasonality peaks from April thorough June." }, { "code": null, "e": 1821, "s": 1722, "text": "m <- prophet(stats)future <- make_future_dataframe(m, periods = 365)forecast <- predict(m, future)" }, { "code": null, "e": 2020, "s": 1821, "text": "Like machine learning models the first command fits a model on the dataframe and next will deploy the model using the predict command in order to receive predictions for the length of days required." }, { "code": null, "e": 2038, "s": 2020, "text": "plot(m, forecast)" }, { "code": null, "e": 2329, "s": 2038, "text": "The out of the box visualizations of the prophet package are quite nice with predefined tick marks, data points and uncertainty intervals. This is one of the advantages of this open source package, no need for extra customization and the first result is fast and good enough for most needs." }, { "code": null, "e": 2447, "s": 2329, "text": "Using this graph we spot the yearly trend and seasonality much clearer and how these are used for making predictions." }, { "code": null, "e": 2507, "s": 2447, "text": "tail(forecast[c(‘ds’, ‘yhat’, ‘yhat_lower’, ‘yhat_upper’)])" }, { "code": null, "e": 2690, "s": 2507, "text": "The forecast object holds the raw data with the predicted value by day and uncertainty intervals. It is also possible to access the prediction trends and seasonality components with:" }, { "code": null, "e": 2705, "s": 2690, "text": "tail(forecast)" }, { "code": null, "e": 2742, "s": 2705, "text": "prophet_plot_components(m, forecast)" }, { "code": null, "e": 2883, "s": 2742, "text": "keeping up with the simplicity, its easy to look into the components of the model. Showing the overall trend, weekly and yearly seasonality." }, { "code": null, "e": 3314, "s": 2883, "text": "The last components graph has shown the raising interest with LeBron James during the NBA playoffs and during the NBA finals. The model at this point recognizes the yearly seasonality which returns every year. On a side note, LeBron James currently holds the record for 6 consecutive years of playing the NBA playoffs starting with Miami and continuing with the Cavaliers. So we should expect the same seasonality year after year." }, { "code": null, "e": 3833, "s": 3314, "text": "Adding holidays and events is a major advantage of the package. Firstly by making the predictions more accurate and allowing the user to take into considerations known future events. The developers had made this customization much easier than prior time series packages in which events and holidays should have been manually changed or ignored in order to make predictions. Think of an e-commerce website that can add all reoccurring campaigns and promotions and set revenue goals based on known future campaign dates." }, { "code": null, "e": 4056, "s": 3833, "text": "Adding events and holidays is done by creating a new dataframe in which we pass the dates of begging or ending of the events and the length of the days. In this example we will add the NBA playoffs and NBA finals as events" }, { "code": null, "e": 4373, "s": 4056, "text": "playoff_brackets <- data_frame( holiday = ‘playoffs’, ds = as.Date(c(‘2017–04–16’ ,’2016–04–17', ‘2015–04–19’, ‘2014–04–19’)), lower_window = 0, upper_window = 45)playoff_finals <- data_frame( holiday = ‘playoff_finals’, ds = as.Date(c(‘2016–06–02’, ‘2015–06–04’, ‘2014–06–05’)), lower_window = 0, upper_window = 20)" }, { "code": null, "e": 4548, "s": 4373, "text": "Using the lower and upper window parameters the user can set the length of the holiday. Those mappings will be row binded to a single object and passed in holidays parameter." }, { "code": null, "e": 4699, "s": 4548, "text": "holidays <- bind_rows(playoff_brackets, playoff_finals)m <- prophet(stats, holidays = playoff_brackets)forecast <- predict(m, future)plot(m, forecast)" }, { "code": null, "e": 4954, "s": 4699, "text": "Notice the model better predicts the values during the peaks. Printing out he components again will show the added row of holidays effect on prediction. Theoretically you can map many events which are critical for the business and get better predictions." }, { "code": null, "e": 5310, "s": 4954, "text": "When building predictions it is important to remove outliers from the historical data. The data points are used by the model which adds their effect to the predictions although they are single time events or just false event logs. Unlike other packages that will breakdown when passed an NA value with the historical data, Prophet will ignore those dates." }, { "code": null, "e": 5500, "s": 5310, "text": "In this example we will remove a series of single time event in which the NBA player announced he is leaving Miami in favor of Cleveland which probably draw attention to his Wikipedia page." }, { "code": null, "e": 5622, "s": 5500, "text": "outliers <- (as.Date(stats$ds) > as.Date(‘2014–07–09’) & as.Date(stats$ds) < as.Date(‘2014–07–12’))stats$y[outliers] = NA" }, { "code": null, "e": 5787, "s": 5622, "text": "At this point we can see the simplicity and robust the developers had in mind when creating this package. Some extra functionality I didn’t show but should be used:" }, { "code": null, "e": 5834, "s": 5787, "text": "Changing seasonality and holidays effect scale" }, { "code": null, "e": 5871, "s": 5834, "text": "Mapping critical trend change points" }, { "code": null, "e": 5901, "s": 5871, "text": "Editing uncertainty Intervals" }, { "code": null, "e": 6134, "s": 5901, "text": "The next step I hope the developers will take is using this package and leverage it for anomaly detection for time series data. Prior packages offer such functionality but depend heavily on the data structure and strict seasonality." }, { "code": null, "e": 6324, "s": 6134, "text": "Lets use the existing model in order to map anomalies in the data. We will compare the original values (y) with the predicted model values (yhat) and create a new column called diff_values." }, { "code": null, "e": 6587, "s": 6324, "text": "combined_data <- cbind(head(forecast, nrow(stats)), stats[order(stats$ds),])combined_data$diff_values <- (combined_data$y - combined_data$yhat)summary(combined_data$diff_values)Min. 1st Qu. Median Mean 3rd Qu. Max. 0.05269 0.07326 0.10780 0.13490 0.16520 0.29480" }, { "code": null, "e": 6735, "s": 6587, "text": "To better generalize the detection of anomalies we will also add the normalized diff values representing the percent difference from actual values." }, { "code": null, "e": 6831, "s": 6735, "text": "combined_data$diff_values_normalized <-(combined_data$y - combined_data$yhat) / combined_data$y" }, { "code": null, "e": 6897, "s": 6831, "text": "Lets go ahead and visualize the normalized diff values over time." }, { "code": null, "e": 6958, "s": 6897, "text": "plot(diff_values_normalized ~ ds, combined_data, type = “l”)" }, { "code": null, "e": 7299, "s": 6958, "text": "Most predictions are quite close to the actual values as the graph tends to move around the 0 value. We can also ask what percent of data points are anomalies by filtering the absolute of the column diff_values_normalized. Setting a threshold from which a data point is considered a anomaly is one way to look at it. In this example its 10%" }, { "code": null, "e": 7416, "s": 7299, "text": "nrow(combined_data[abs(combined_data$diff_values_normalized) > 0.1& !is.na(combined_data$y),]) / nrow(combined_data)" }, { "code": null, "e": 7515, "s": 7416, "text": "We receive 0.02 which indicates that 2% of data points are anomalies based on the given threshold." }, { "code": null, "e": 7813, "s": 7515, "text": "Making predictions is an important skill for data professionals. Thanks for open sourced projects like Prophet this does not need to be too difficult. This package balances between simplicity, computation speed and the right amount of customization so both beginners and advanced users can use it." } ]
Java Cryptography - Verifying Signature
You can create digital signature using Java and verify it following the steps given below. The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys. Create KeyPairGenerator object using the getInstance() method as shown below. //Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA"); The KeyPairGenerator class provides a method named initialize() method. This method is used to initialize the key pair generator. This method accepts an integer value representing the key size. Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below. //Initializing the KeyPairGenerator keyPairGen.initialize(2048); You can generate the KeyPair using the generateKeyPair() method. Generate the keypair using this method as shown below. //Generate the pair of keys KeyPair pair = keyPairGen.generateKeyPair(); You can get the private key from the generated KeyPair object using the getPrivate() method. Get the private key using the getPrivate() method as shown below. //Getting the private key from the key pair PrivateKey privKey = pair.getPrivate(); The getInstance() method of the Signature class accepts a string parameter representing required signature algorithm and returns the respective Signature object. Create an object of the Signature class using the getInstance() method. //Creating a Signature object Signature sign = Signature.getInstance("SHA256withDSA"); The initSign() method of the Signature class accepts a PrivateKey object and initializes the current Signature object. Initialize the Signature object created in the previous step using the initSign() method as shown below. //Initialize the signature sign.initSign(privKey); The update() method of the Signature class accepts a byte array representing the data to be signed or verified and updates the current object with the data given. Update the initialized Signature object by passing the data to be signed to the update() method in the form of byte array as shown below. byte[] bytes = "Hello how are you".getBytes(); //Adding data to the signature sign.update(bytes); The sign() method of the Signature class returns the signature bytes of the updated data. Calculate the Signature using the sign() method as shown below. //Calculating the signature byte[] signature = sign.sign(); To verify a Signature object you need to initialize it first using the initVerify() method it method accepts a PublicKey object. Therefore, initialize the Signature object for verification using the initVerify() method as shown below. //Initializing the signature sign.initVerify(pair.getPublic()); Update the initialized (for verification) object with the data the data to be verified using the update method as shown below. //Update the data to be verified sign.update(bytes); The verify() method of the Signature class accepts another signature object and verifies it with the current one. If a match occurs, it returns true else it returns false. Verify the signature using this method as shown below. //Verify the signature boolean bool = sign.verify(signature); Following Java program accepts a message from the user, generates a digital signature for the given message, and verifies it. import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.Signature; import java.util.Scanner; public class SignatureVerification { public static void main(String args[]) throws Exception{ //Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA"); //Initializing the key pair generator keyPairGen.initialize(2048); //Generate the pair of keys KeyPair pair = keyPairGen.generateKeyPair(); //Getting the privatekey from the key pair PrivateKey privKey = pair.getPrivate(); //Creating a Signature object Signature sign = Signature.getInstance("SHA256withDSA"); //Initializing the signature sign.initSign(privKey); byte[] bytes = "Hello how are you".getBytes(); //Adding data to the signature sign.update(bytes); //Calculating the signature byte[] signature = sign.sign(); //Initializing the signature sign.initVerify(pair.getPublic()); sign.update(bytes); //Verifying the signature boolean bool = sign.verify(signature); if(bool) { System.out.println("Signature verified"); } else { System.out.println("Signature failed"); } } } The above program generates the following output − Signature verified 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": 2144, "s": 2053, "text": "You can create digital signature using Java and verify it following the steps given below." }, { "code": null, "e": 2343, "s": 2144, "text": "The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys." }, { "code": null, "e": 2421, "s": 2343, "text": "Create KeyPairGenerator object using the getInstance() method as shown below." }, { "code": null, "e": 2525, "s": 2421, "text": "//Creating KeyPair generator object\nKeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n" }, { "code": null, "e": 2719, "s": 2525, "text": "The KeyPairGenerator class provides a method named initialize() method. This method is used to initialize the key pair generator. This method accepts an integer value representing the key size." }, { "code": null, "e": 2833, "s": 2719, "text": "Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below." }, { "code": null, "e": 2899, "s": 2833, "text": "//Initializing the KeyPairGenerator\nkeyPairGen.initialize(2048);\n" }, { "code": null, "e": 3019, "s": 2899, "text": "You can generate the KeyPair using the generateKeyPair() method. Generate the keypair using this method as shown below." }, { "code": null, "e": 3093, "s": 3019, "text": "//Generate the pair of keys\nKeyPair pair = keyPairGen.generateKeyPair();\n" }, { "code": null, "e": 3186, "s": 3093, "text": "You can get the private key from the generated KeyPair object using the getPrivate() method." }, { "code": null, "e": 3252, "s": 3186, "text": "Get the private key using the getPrivate() method as shown below." }, { "code": null, "e": 3340, "s": 3252, "text": "//Getting the private key from the key pair\nPrivateKey privKey = pair.getPrivate(); \n" }, { "code": null, "e": 3502, "s": 3340, "text": "The getInstance() method of the Signature class accepts a string parameter representing required signature algorithm and returns the respective Signature object." }, { "code": null, "e": 3574, "s": 3502, "text": "Create an object of the Signature class using the getInstance() method." }, { "code": null, "e": 3662, "s": 3574, "text": "//Creating a Signature object\nSignature sign = Signature.getInstance(\"SHA256withDSA\");\n" }, { "code": null, "e": 3781, "s": 3662, "text": "The initSign() method of the Signature class accepts a PrivateKey object and initializes the current Signature object." }, { "code": null, "e": 3886, "s": 3781, "text": "Initialize the Signature object created in the previous step using the initSign() method as shown below." }, { "code": null, "e": 3938, "s": 3886, "text": "//Initialize the signature\nsign.initSign(privKey);\n" }, { "code": null, "e": 4101, "s": 3938, "text": "The update() method of the Signature class accepts a byte array representing the data to be signed or verified and updates the current object with the data given." }, { "code": null, "e": 4239, "s": 4101, "text": "Update the initialized Signature object by passing the data to be signed to the update() method in the form of byte array as shown below." }, { "code": null, "e": 4345, "s": 4239, "text": "byte[] bytes = \"Hello how are you\".getBytes(); \n\n//Adding data to the signature\nsign.update(bytes);\n" }, { "code": null, "e": 4435, "s": 4345, "text": "The sign() method of the Signature class returns the signature bytes of the updated data." }, { "code": null, "e": 4499, "s": 4435, "text": "Calculate the Signature using the sign() method as shown below." }, { "code": null, "e": 4560, "s": 4499, "text": "//Calculating the signature\nbyte[] signature = sign.sign();\n" }, { "code": null, "e": 4689, "s": 4560, "text": "To verify a Signature object you need to initialize it first using the initVerify() method it method accepts a PublicKey object." }, { "code": null, "e": 4795, "s": 4689, "text": "Therefore, initialize the Signature object for verification using the initVerify() method as shown below." }, { "code": null, "e": 4860, "s": 4795, "text": "//Initializing the signature\nsign.initVerify(pair.getPublic());\n" }, { "code": null, "e": 4987, "s": 4860, "text": "Update the initialized (for verification) object with the data the data to be verified using the update method as shown below." }, { "code": null, "e": 5041, "s": 4987, "text": "//Update the data to be verified\nsign.update(bytes);\n" }, { "code": null, "e": 5213, "s": 5041, "text": "The verify() method of the Signature class accepts another signature object and verifies it with the current one. If a match occurs, it returns true else it returns false." }, { "code": null, "e": 5268, "s": 5213, "text": "Verify the signature using this method as shown below." }, { "code": null, "e": 5331, "s": 5268, "text": "//Verify the signature\nboolean bool = sign.verify(signature);\n" }, { "code": null, "e": 5457, "s": 5331, "text": "Following Java program accepts a message from the user, generates a digital signature for the given message, and verifies it." }, { "code": null, "e": 6837, "s": 5457, "text": "import java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.PrivateKey;\nimport java.security.Signature;\n\nimport java.util.Scanner;\n\npublic class SignatureVerification {\n public static void main(String args[]) throws Exception{\n //Creating KeyPair generator object\n KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n\t \n //Initializing the key pair generator\n keyPairGen.initialize(2048);\n\t \n //Generate the pair of keys\n KeyPair pair = keyPairGen.generateKeyPair();\n \n //Getting the privatekey from the key pair\n PrivateKey privKey = pair.getPrivate();\n\n //Creating a Signature object\n Signature sign = Signature.getInstance(\"SHA256withDSA\");\n\n //Initializing the signature\n sign.initSign(privKey);\n byte[] bytes = \"Hello how are you\".getBytes();\n \n //Adding data to the signature\n sign.update(bytes);\n \n //Calculating the signature\n byte[] signature = sign.sign(); \n \n //Initializing the signature\n sign.initVerify(pair.getPublic());\n sign.update(bytes);\n \n //Verifying the signature\n boolean bool = sign.verify(signature);\n \n if(bool) {\n System.out.println(\"Signature verified\"); \n } else {\n System.out.println(\"Signature failed\");\n }\n }\n}" }, { "code": null, "e": 6888, "s": 6837, "text": "The above program generates the following output −" }, { "code": null, "e": 6908, "s": 6888, "text": "Signature verified\n" }, { "code": null, "e": 6941, "s": 6908, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6957, "s": 6941, "text": " Malhar Lathkar" }, { "code": null, "e": 6990, "s": 6957, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7006, "s": 6990, "text": " Malhar Lathkar" }, { "code": null, "e": 7041, "s": 7006, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7055, "s": 7041, "text": " Anadi Sharma" }, { "code": null, "e": 7089, "s": 7055, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7103, "s": 7089, "text": " Tushar Kale" }, { "code": null, "e": 7140, "s": 7103, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7155, "s": 7140, "text": " Monica Mittal" }, { "code": null, "e": 7188, "s": 7155, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7207, "s": 7188, "text": " Arnab Chakraborty" }, { "code": null, "e": 7214, "s": 7207, "text": " Print" }, { "code": null, "e": 7225, "s": 7214, "text": " Add Notes" } ]
SAS - Macros
SAS has a powerful programming feature called Macros which allows us to avoid repetitive sections of code and to use them again and again when needed. It also helps create dynamic variables within the code that can take different values for different run instances of the same code. Macros can also be declared for blocks of code which will be reused multiple times in a similar manner to macro variables. We will see both of these in the below examples. These are the variables which hold a value to be used again and again by a SAS program. They are declared at the beginning of a SAS program and called out later in the body of the program. They can be Global or Local in scope. They are called global macro variables because they can accessed by any SAS program available in the SAS environment. In general they are the system assigned variables which are accessed by multiple programs. A general example is the system date. Below is a example of the SAS variable called SYSDATE which represents the system date. Consider a scenario to print the system date in the title of the SAS report every day the report is generated. The title will show the current date and day without we coding any values for them. We use the in-built SAS data set called CARS available in the SASHELP library. proc print data = sashelp.cars; where make = 'Audi' and type = 'Sports' ; TITLE "Sales as of &SYSDAY &SYSDATE"; run; When the above code is run we get the following output. These variables can be accessed by SAS programs in which they are declared as part of the program. They are typically used to supply different variables to the same SAS statements sl that they can process different observations of a data set. The local variables are declared with below syntax. % LET (Macro Variable Name) = Value; Here the Value field can take any numeric, text or date value as required by the program. The Macro variable name is any valid SAS variable. The variables are used by the SAS statements using the & character appended at the beginning of the variable name. Below program gets us all the observation of the make 'Audi' and type 'Sports'. In case we want the result of different make, we need to change the value of the variable make_name without changing any other part of the program. In case of bring programs this variable can be referred again and again in any SAS statements. %LET make_name = 'Audi'; %LET type_name = 'Sports'; proc print data = sashelp.cars; where make = &make_name and type = &type_name ; TITLE "Sales as of &SYSDAY &SYSDATE"; run; When the above code is run we get the same output as the previous program. But let’s change the type name to 'Wagon' and run the same program. We will get the below result. Macro is a group of SAS statements that is referred by a name and to use it in program anywhere, using that name. It starts with a %MACRO statement and ends with %MEND statement. The local variables are declared with below syntax. # Creating a Macro program. %MACRO <macro name>(Param1, Param2,....Paramn); Macro Statements; %MEND; # Calling a Macro program. %MacroName (Value1, Value2,.....Valuen); The below program decalres a group of SAT staemnets under a macro named 'show_result'; This Macro is being called by other SAS statements. %MACRO show_result(make_ , type_); proc print data = sashelp.cars; where make = "&make_" and type = "&type_" ; TITLE "Sales as of &SYSDAY &SYSDATE"; run; %MEND; %show_result(BMW,SUV); When the above code is run we get the following output. SAS has many MACRO statements which are in-built in the SAS programming language. They are used by other SAS programs without explicitly declaring them.Common examples are - terminating a program when some condition is met or capturing the runtime value of a variable in the program log. Below are some examples. This macro statement writes text or macro variable information to the SAS log. In the below example the value of the variable 'today' is written to the program log. data _null_; CALL SYMPUT ('today', TRIM(PUT("&sysdate"d,worddate22.))); run; %put &today; When the above code is run we get the following output. Execution of this macro causes normal termination of the currently executing macro when certain condition evaluates to be true. In the below examplewhen the value of the variable "val" becomes 10, the macro terminates else it contnues. %macro check_condition(val); %if &val = 10 %then %return; data p; x = 34.2; run; %mend check_condition; %check_condition(11) ; When the above code is run we get the following output. This macro definition contains a %DO %WHILE loop that ends, as required, with a %END statement. In the below example the macro named test takes a user input and runs the DO loop using this input value. The end of DO loop is achieved through the %end statement while the end of macro is achieved through %mend statement. %macro test(finish); %let i = 1; %do %while (&i <&finish); %put the value of i is &i; %let i=%eval(&i+1); %end; %mend test; %test(5) When the above code is run we get the following output. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 3038, "s": 2583, "text": "SAS has a powerful programming feature called Macros which allows us to avoid repetitive sections of code and to use them again and again when needed. It also helps create dynamic variables within the code that can take different values for different run instances of the same code. Macros can also be declared for blocks of code which will be reused multiple times in a similar manner to macro variables. We will see both of these in the below examples." }, { "code": null, "e": 3265, "s": 3038, "text": "These are the variables which hold a value to be used again and again by a SAS program. They are declared at the beginning of a SAS program and called out later in the body of the program. They can be Global or Local in scope." }, { "code": null, "e": 3512, "s": 3265, "text": "They are called global macro variables because they can accessed by any SAS program available in the SAS environment. In general they are the system assigned variables which are accessed by multiple programs. A general example is the system date." }, { "code": null, "e": 3874, "s": 3512, "text": "Below is a example of the SAS variable called SYSDATE which represents the system date. Consider a scenario to print the system date in the title of the SAS report every day the report is generated. The title will show the current date and day without we coding any values for them. We use the in-built SAS data set called CARS available in the SASHELP library." }, { "code": null, "e": 3995, "s": 3874, "text": "proc print data = sashelp.cars;\nwhere make = 'Audi' and type = 'Sports' ;\n TITLE \"Sales as of &SYSDAY &SYSDATE\";\nrun;\n" }, { "code": null, "e": 4051, "s": 3995, "text": "When the above code is run we get the following output." }, { "code": null, "e": 4294, "s": 4051, "text": "These variables can be accessed by SAS programs in which they are declared as part of the program. They are typically used to supply different variables to the same SAS statements sl that they can process different observations of a data set." }, { "code": null, "e": 4346, "s": 4294, "text": "The local variables are declared with below syntax." }, { "code": null, "e": 4384, "s": 4346, "text": "% LET (Macro Variable Name) = Value;\n" }, { "code": null, "e": 4525, "s": 4384, "text": "Here the Value field can take any numeric, text or date value as required by the program. The Macro variable name is any valid SAS variable." }, { "code": null, "e": 4963, "s": 4525, "text": "The variables are used by the SAS statements using the & character appended at the beginning of the variable name. Below program gets us all the observation of the make 'Audi' and type 'Sports'. In case we want the result of different make, we need to change the value of the variable make_name without changing any other part of the program. In case of bring programs this variable can be referred again and again in any SAS statements." }, { "code": null, "e": 5142, "s": 4963, "text": "%LET make_name = 'Audi';\n%LET type_name = 'Sports';\nproc print data = sashelp.cars;\nwhere make = &make_name and type = &type_name ;\n TITLE \"Sales as of &SYSDAY &SYSDATE\";\nrun;\n" }, { "code": null, "e": 5315, "s": 5142, "text": "When the above code is run we get the same output as the previous program. But let’s change the type name to 'Wagon' and run the same program. We will get the below result." }, { "code": null, "e": 5494, "s": 5315, "text": "Macro is a group of SAS statements that is referred by a name and to use it in program anywhere, using that name. It starts with a %MACRO statement and ends with %MEND statement." }, { "code": null, "e": 5546, "s": 5494, "text": "The local variables are declared with below syntax." }, { "code": null, "e": 5719, "s": 5546, "text": "# Creating a Macro program.\n%MACRO <macro name>(Param1, Param2,....Paramn);\n\nMacro Statements;\n\n%MEND;\n\n# Calling a Macro program.\n%MacroName (Value1, Value2,.....Valuen);\n" }, { "code": null, "e": 5858, "s": 5719, "text": "The below program decalres a group of SAT staemnets under a macro named 'show_result'; This Macro is being called by other SAS statements." }, { "code": null, "e": 6047, "s": 5858, "text": "%MACRO show_result(make_ , type_);\nproc print data = sashelp.cars;\nwhere make = \"&make_\" and type = \"&type_\" ;\n TITLE \"Sales as of &SYSDAY &SYSDATE\";\nrun;\n%MEND;\n\n%show_result(BMW,SUV);\n" }, { "code": null, "e": 6103, "s": 6047, "text": "When the above code is run we get the following output." }, { "code": null, "e": 6416, "s": 6103, "text": "SAS has many MACRO statements which are in-built in the SAS programming language. They are used by other SAS programs without explicitly declaring them.Common examples are - terminating a program when some condition is met or capturing the runtime value of a variable in the program log. Below are some examples." }, { "code": null, "e": 6581, "s": 6416, "text": "This macro statement writes text or macro variable information to the SAS log. In the below example the value of the variable 'today' is written to the program log." }, { "code": null, "e": 6672, "s": 6581, "text": "data _null_;\nCALL SYMPUT ('today',\nTRIM(PUT(\"&sysdate\"d,worddate22.)));\nrun;\n%put &today;\n" }, { "code": null, "e": 6728, "s": 6672, "text": "When the above code is run we get the following output." }, { "code": null, "e": 6964, "s": 6728, "text": "Execution of this macro causes normal termination of the currently executing macro when certain condition evaluates to be true. In the below examplewhen the value of the variable \"val\" becomes 10, the macro terminates else it contnues." }, { "code": null, "e": 7115, "s": 6964, "text": "%macro check_condition(val);\n %if &val = 10 %then %return;\n\n data p;\n x = 34.2;\n run; \n\n%mend check_condition; \n\n%check_condition(11) ;\n" }, { "code": null, "e": 7171, "s": 7115, "text": "When the above code is run we get the following output." }, { "code": null, "e": 7491, "s": 7171, "text": "This macro definition contains a %DO %WHILE loop that ends, as required, with a %END statement. In the below example the macro named test takes a user input and runs the DO loop using this input value.\nThe end of DO loop is achieved through the %end statement while the end of macro is achieved through %mend statement." }, { "code": null, "e": 7646, "s": 7491, "text": "%macro test(finish);\n %let i = 1;\n %do %while (&i <&finish);\n %put the value of i is &i;\n %let i=%eval(&i+1);\n %end;\n%mend test;\n%test(5)\n" }, { "code": null, "e": 7702, "s": 7646, "text": "When the above code is run we get the following output." }, { "code": null, "e": 7737, "s": 7702, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7754, "s": 7737, "text": " Code And Create" }, { "code": null, "e": 7789, "s": 7754, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 7802, "s": 7789, "text": " Juan Galvan" }, { "code": null, "e": 7839, "s": 7802, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 7859, "s": 7839, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 7894, "s": 7859, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7907, "s": 7894, "text": " Ermin Dedic" }, { "code": null, "e": 7944, "s": 7907, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 7960, "s": 7944, "text": " Muslim Helalee" }, { "code": null, "e": 7967, "s": 7960, "text": " Print" }, { "code": null, "e": 7978, "s": 7967, "text": " Add Notes" } ]
Increase and decrease row value by 1 in MySQL with Stored Procedure?
Let us first create a table to increase and adecrease row value by 1. The following is the query − mysql> create table IncrementAndDecrementValue −> ( −> UserId int, −> UserScores int −> ); Query OK, 0 rows affected (0.60 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into IncrementAndDecrementValue values(101,20000); Query OK, 1 row affected (0.13 sec) mysql> insert into IncrementAndDecrementValue values(102,30000); Query OK, 1 row affected (0.20 sec) mysql> insert into IncrementAndDecrementValue values(103,40000); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from IncrementAndDecrementValue; The following is the output − +--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 20000 | | 102 | 30000 | | 103 | 40000 | +--------+------------+ 3 rows in set (0.00 sec) Here is my stored procedure to increase and decrease row value by 1. mysql> delimiter // mysql> create procedure IncrementAndDecrementRowValueByOne() −> begin −> declare first int; −> declare second int; −> set first = (select UserScores from IncrementAndDecrementValue where UserId = 101); −> set second = (select UserScores from IncrementAndDecrementValue where UserId = 102); −> update IncrementAndDecrementValue set UserScores = first-1 where UserId = 101; −> update IncrementAndDecrementValue set UserScores = second+1 where UserId = 102; −> end // Query OK, 0 rows affected (0.17 sec) mysql> delimiter ; Call the stored procedure using CALL command. The query is as follows − mysql> call IncrementAndDecrementRowValueByOne(); Query OK, 1 row affected (0.24 sec) Check the row value is updated or not using select statement. The query is as follows − mysql> select *from IncrementAndDecrementValue; The following is the output − +--------+------------+ | UserId | UserScores | +--------+------------+ | 101 | 19999 | | 102 | 30001 | | 103 | 40000 | +--------+------------+ 3 rows in set (0.00 sec) We have decremented the value 20000 to 19999 and incremented 30000 to 30001.
[ { "code": null, "e": 1161, "s": 1062, "text": "Let us first create a table to increase and adecrease row value by 1. The following is the query −" }, { "code": null, "e": 1301, "s": 1161, "text": "mysql> create table IncrementAndDecrementValue\n −> (\n −> UserId int,\n −> UserScores int\n −> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1382, "s": 1301, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1687, "s": 1382, "text": "mysql> insert into IncrementAndDecrementValue values(101,20000);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into IncrementAndDecrementValue values(102,30000);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into IncrementAndDecrementValue values(103,40000);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1772, "s": 1687, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 1820, "s": 1772, "text": "mysql> select *from IncrementAndDecrementValue;" }, { "code": null, "e": 1850, "s": 1820, "text": "The following is the output −" }, { "code": null, "e": 2043, "s": 1850, "text": "+--------+------------+\n| UserId | UserScores |\n+--------+------------+\n| 101 | 20000 |\n| 102 | 30000 |\n| 103 | 40000 |\n+--------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2112, "s": 2043, "text": "Here is my stored procedure to increase and decrease row value by 1." }, { "code": null, "e": 2679, "s": 2112, "text": "mysql> delimiter //\n\nmysql> create procedure IncrementAndDecrementRowValueByOne()\n −> begin\n −> declare first int;\n −> declare second int;\n −> set first = (select UserScores from IncrementAndDecrementValue where UserId = 101);\n −> set second = (select UserScores from IncrementAndDecrementValue where UserId = 102);\n −> update IncrementAndDecrementValue set UserScores = first-1 where UserId = 101;\n −> update IncrementAndDecrementValue set UserScores = second+1 where UserId = 102;\n −> end //\nQuery OK, 0 rows affected (0.17 sec)\n\nmysql> delimiter ;" }, { "code": null, "e": 2751, "s": 2679, "text": "Call the stored procedure using CALL command. The query is as follows −" }, { "code": null, "e": 2837, "s": 2751, "text": "mysql> call IncrementAndDecrementRowValueByOne();\nQuery OK, 1 row affected (0.24 sec)" }, { "code": null, "e": 2925, "s": 2837, "text": "Check the row value is updated or not using select statement. The query is as follows −" }, { "code": null, "e": 2973, "s": 2925, "text": "mysql> select *from IncrementAndDecrementValue;" }, { "code": null, "e": 3003, "s": 2973, "text": "The following is the output −" }, { "code": null, "e": 3196, "s": 3003, "text": "+--------+------------+\n| UserId | UserScores |\n+--------+------------+\n| 101 | 19999 |\n| 102 | 30001 |\n| 103 | 40000 |\n+--------+------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 3273, "s": 3196, "text": "We have decremented the value 20000 to 19999 and incremented 30000 to 30001." } ]
Ionic - Quick Guide
Ionic is a front-end HTML framework built on top of AngularJS and Cordova. As per their official document, the definition of this Ionic Open Source Framework is as follows − Ionic is an HTML5 Mobile App Development Framework targeted at building hybrid mobile apps. Think of Ionic as the front-end UI framework that handles all the look and feel and UI interactions your app needs to be compelling. Kind of like "Bootstrap for Native", but with the support for a broad range of common native mobile components, slick animations and a beautiful design. Following are the most important features of Ionic − AngularJS − Ionic is using AngularJS MVC architecture for building rich single page applications optimized for mobile devices. AngularJS − Ionic is using AngularJS MVC architecture for building rich single page applications optimized for mobile devices. CSS components − With the native look and feel, these components offer almost all elements that a mobile application needs. The components’ default styling can be easily overridden to accommodate your own designs. CSS components − With the native look and feel, these components offer almost all elements that a mobile application needs. The components’ default styling can be easily overridden to accommodate your own designs. JavaScript components − These components are extending CSS components with JavaScript functionalities to cover all mobile elements that cannot be done only with HTML and CSS. JavaScript components − These components are extending CSS components with JavaScript functionalities to cover all mobile elements that cannot be done only with HTML and CSS. Cordova Plugins − Apache Cordova plugins offer API needed for using native device functions with JavaScript code. Cordova Plugins − Apache Cordova plugins offer API needed for using native device functions with JavaScript code. Ionic CLI − This is NodeJS utility powered with commands for starting, building, running and emulating Ionic applications. Ionic CLI − This is NodeJS utility powered with commands for starting, building, running and emulating Ionic applications. Ionic View − Very useful platform for uploading, sharing and testing your application on native devices. Ionic View − Very useful platform for uploading, sharing and testing your application on native devices. Licence − Ionic is released under MIT license. Licence − Ionic is released under MIT license. Following are some of the most commonly known Ionic Framework Advantages − Ionic is used for Hybrid App Development. This means that you can package your applications for IOS, Android, Windows Phone and Firefox OS, which can save you a lot of working time. Ionic is used for Hybrid App Development. This means that you can package your applications for IOS, Android, Windows Phone and Firefox OS, which can save you a lot of working time. Starting your app is very easy since Ionic provides useful pre-generated app setup with simple layouts. Starting your app is very easy since Ionic provides useful pre-generated app setup with simple layouts. The apps are built in a very clean and modular way, so it is very maintainable and easy to update. The apps are built in a very clean and modular way, so it is very maintainable and easy to update. Ionic Developers Team have a very good relationship with the Google Developers Team and they are working together to improve the framework. The updates are coming out regularly and Ionic support group is always willing to help when needed. Ionic Developers Team have a very good relationship with the Google Developers Team and they are working together to improve the framework. The updates are coming out regularly and Ionic support group is always willing to help when needed. Following are some of the most important Ionic Framework Limitations − Testing can be tricky since the browser does not always give you the right information about the phone environment. There are so many different devices as well as platforms and you usually need to cover most of them. Testing can be tricky since the browser does not always give you the right information about the phone environment. There are so many different devices as well as platforms and you usually need to cover most of them. It can be hard to combine different native functionalities. There will be many instances where you would run into plugin compatibility issues, which leads to build errors that are hard to debug. It can be hard to combine different native functionalities. There will be many instances where you would run into plugin compatibility issues, which leads to build errors that are hard to debug. Hybrid apps tend to be slower than the native ones. However, since the mobile technologies are improving fast this will not be an issue in the future. Hybrid apps tend to be slower than the native ones. However, since the mobile technologies are improving fast this will not be an issue in the future. In the next chapter, we will understand the environment setup of the Ionic Open Source Framework. This chapter will show you how to start with Ionic Framework. The following table contains the list of components needed to start with Ionic. NodeJS This is the base platform needed to create Mobile Apps using Ionic. You can find detail on the NodeJS installation in our NodeJS Environment Setup. Make sure you also install npm while installing NodeJS. Android SDK If you are going to work on a Windows platform and are developing your apps for the Android platform, then you should have Android SDK setup on your machine. The following link has detailed information on the Android Environment Setup. XCode If you are going to work on the Mac platform and are developing your apps for the iOS platform, then you should have XCode setup on your machine. The following link has detailed information on the iOS Environment Setup. cordova and Ionic These are the main SDKs which is needed to start working with Ionic. This chapter explains how to setup Ionic in simple step assuming you already have the required setup as explained in the table above. We will use the Windows command prompt for this tutorial. The same steps can be applied to the OSX terminal. Open your command window to install Cordova and Ionic − C:\Users\Username> npm install -g cordova ionic While creating apps in Ionic, you can choose from the following three options to start with − Tabs App Blank App Side menu app In your command window, open the folder where you want to create the app and try one of the options mentioned below. If you want to use the Ionic tabs template, the app will be built with the tab menu, header and a couple of useful screens and functionalities. This is the default Ionic template. Open your command window and choose where you want to create your app. C:\Users\Username> cd Desktop This command will change the working directory. The app will be created on the Desktop. C:\Users\Username\Desktop> ionic start myApp tabs Ionic Start command will create a folder named myApp and setup Ionic files and folders. C:\Users\Username\Desktop> cd myApp Now, we want to access the myApp folder that we just created. This is our root folder. Let us now add the Cordova project for the Android Platform and install the basic Cordova plugins as well. The following code allows us to run the app on the Android emulator or a device. C:\Users\Username\Desktop\myApp> ionic platform add android The next step is to build the app. If you have building errors after running the following command, you probably did not install the Android SDK and its dependencies. C:\Users\Username\Desktop\myApp> ionic build android The last step of the installation process is to run your app, which will start the mobile device, if connected, or the default emulator, if there is no device connected. Android Default Emulator is slow, so I suggest you to install Genymotion or some other popular Android Emulator. C:\Users\Username\Desktop\myApp> ionic run android This will produce below result, which is an Ionic Tabs App. If you want to start from the scratch, you can install the Ionic blank template. We will use the same steps that have been explained above with the addition of ionic start myApp blank instead of ionic start myApp tabs as follows. C:\Users\Username\Desktop> ionic start myApp blank The Ionic Start command will create a folder named myApp and setup the Ionic files and folders. C:\Users\Username\Desktop> cd myApp Let us add the Cordova project for the Android Platform and install the basic Cordova plugins as explained above. C:\Users\Username\Desktop\myApp>ionic platform add android The next step is to build our app − C:\Users\Username\Desktop\myApp> ionic build android Finally, we will start the App as with the following code − C:\Users\Username\Desktop\myApp> ionic run android This will produce the following result, which is a Ionic Blank App. The third template that you can use is the Side Menu Template. The steps are the same as the previous two templates; we will just add sidemenu when starting our app as shown in the code below. C:\Users\Username\Desktop> ionic start myApp sidemenu The Ionic Start command will create a folder named myApp and setup the Ionic files and folders. C:\Users\Username\Desktop> cd myApp Let us add the Cordova project for the Android Platform and install the basic Cordova plugins with the code given below. C:\Users\Username\Desktop\myApp> ionic platform add android The next step is to build our app with the following code. C:\Users\Username\Desktop\myApp> ionic build android Finally, we will start the App with the code given below. C:\Users\Username\Desktop\myApp> ionic run android This will produce the following result, which is an Ionic Side Menu App. Since we are working with the JavaScript, you can serve your app on any web browser. This will speed up your building process, but you should always test your app on native emulators and devices. Type the following code to serve your app on the web browser. C:\Users\Username\Desktop\myApp> ionic serve The above command will open your app in the web browser. Google Chrome provides the device mode functionality for mobile development testing. Press F12 to access the developer console. The top left corner of the console window click has the "Toggle Device Mode" icon. The next step will be to click "Dock to Right" icon in the top right corner. Once the page is refreshed, you should be ready for testing on the web browser. Ionic creates the following directory structure for all type of apps. This is important for any Ionic developer to understand the purpose of every directory and the files mentioned below − Let us have a quick understanding of all the folders and files available in the project folder structure shown in the image above. Hooks − Hooks are scripts that can be triggered during the build process. They are usually used for the Cordova commands customization and for building automated processes. We will not use this folder during this tutorial. Hooks − Hooks are scripts that can be triggered during the build process. They are usually used for the Cordova commands customization and for building automated processes. We will not use this folder during this tutorial. Platforms − This is the folder where Android and IOS projects are created. You might encounter some platform specific problems during development that will require these files, but you should leave them intact most of the time. Platforms − This is the folder where Android and IOS projects are created. You might encounter some platform specific problems during development that will require these files, but you should leave them intact most of the time. Plugins − This folder contains Cordova plugins. When you initially create an Ionic app, some of the plugins will be installed. We will show you how to install Cordova plugins in our subsequent chapters. Plugins − This folder contains Cordova plugins. When you initially create an Ionic app, some of the plugins will be installed. We will show you how to install Cordova plugins in our subsequent chapters. Resources − This folder is used for adding resources like icon and splash screen to your project. Resources − This folder is used for adding resources like icon and splash screen to your project. Scss − Since Ionic core is built with Sass, this is the folder where your Sass file is located. For simplifying the process, we will not use Sass for this tutorial. Our styling will be done using CSS. Scss − Since Ionic core is built with Sass, this is the folder where your Sass file is located. For simplifying the process, we will not use Sass for this tutorial. Our styling will be done using CSS. www − www is the main working folder for Ionic developers. They spend most of their time here. Ionic gives us their default folder structure inside 'www', but the developers can always change it to accommodate their own needs. When this folder is opened, you will find the following sub-folders − The css folder, where you will write your CSS styling. The img folder for storing images. The js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders. The libs folder, where your libraries will be placed. The templates folder for your HTML files. Index.html as a starting point to your app. www − www is the main working folder for Ionic developers. They spend most of their time here. Ionic gives us their default folder structure inside 'www', but the developers can always change it to accommodate their own needs. When this folder is opened, you will find the following sub-folders − The css folder, where you will write your CSS styling. The css folder, where you will write your CSS styling. The img folder for storing images. The img folder for storing images. The js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders. The js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders. The libs folder, where your libraries will be placed. The libs folder, where your libraries will be placed. The templates folder for your HTML files. The templates folder for your HTML files. Index.html as a starting point to your app. Index.html as a starting point to your app. Other Files − Since this is a beginner’s tutorial, we will just mention some of the other important files and their purposes as well. .bowerrc is the bower configuration file. .editorconfig is the editor configuration file. .gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository. bower.json will contain the bower components and dependencies, if you choose to use the bower package manager. gulpfile.js is used for creating automated tasks using the gulp task manager. config.xml is the Cordova configuration file. package.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager. Other Files − Since this is a beginner’s tutorial, we will just mention some of the other important files and their purposes as well. .bowerrc is the bower configuration file. .bowerrc is the bower configuration file. .editorconfig is the editor configuration file. .editorconfig is the editor configuration file. .gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository. .gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository. bower.json will contain the bower components and dependencies, if you choose to use the bower package manager. bower.json will contain the bower components and dependencies, if you choose to use the bower package manager. gulpfile.js is used for creating automated tasks using the gulp task manager. gulpfile.js is used for creating automated tasks using the gulp task manager. config.xml is the Cordova configuration file. config.xml is the Cordova configuration file. package.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager. package.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager. In the next chapter, we will discuss the different colors available in Ionic open source framework. Before we start with actual elements available in the Ionic framework, let us have a little understanding on how Ionic makes use of colors for different elements. Ionic framework gives us a set of nine predefined color classes. You can use these colors or you can override it with your own styling. The following table shows the default set of nine colors provided by Ionic. We will use these colors for styling different Ionic elements in this tutorial. For now, you can check all the colors as shown below − Ionic makes use of different classes for each element. For example, a header element will have bar class and a button will have a button class. To simplify the usage, we use different colors by prefixing element class in a color name. For example, to create a blue color header, we will use a bar-calm as follows − <div class = "bar bar-header bar-calm"> ... </div> Similarly, to create a grey color button, we will use button-stable class as follows. <div class = "button button-stable"> ... </div> You can also use Ionic color class like any other CSS class. We will now style two paragraphs with a balanced (green) and an energized (yellow) color. <p class = "balanced">Paragraph 1...</p> <p class = "energized">Paragraph 2...</p> The above code will produce the following screen − We will discuss in detail in the subsequent chapters, when we create different elements using different classes. When you want to change some of the Ionic default colors using CSS, you can do it by editing the lib/css/ionic.css file. In some cases, this approach is not very productive because every element (header, button, footer...) uses its own classes for styling. Therefore, if you want to change the color of the "light" class to orange, you would need to search through all the elements that use this class and change it. This is useful when you want to change the color of a single element, but not very practical for changing color of all elements because it would use too much time. SASS (which is the short form of – Syntactically Awesome Style Sheet) provides an easier way to change the color for all the elements at once. If you want to use SASS, open your project in the command window and type − C:\Users\Username\Desktop\tutorialApp> ionic setup sass This will set up SASS for your project. Now you can the change default colors by opening the scss/ionic.app.scss file and then typing in the following code before this line – @import "www/lib/ionic/scss/ionic"; We will change the balanced color to dark blue and the energized color to orange. The two paragraphs that we used above are now dark blue and orange. $balanced: #000066 !default; $energized: #FFA500 !default; Now, if you use the following example − <p class = "balanced">Paragraph 1...</p> <p class = "energized">Paragraph 2...</p> The above code will produce the following screen − All the Ionic elements that are using these classes will change to dark blue and orange. Take into consideration that you do not need to use Ionic default color classes. You can always style elements the way you want. The www/css/style.css file will be removed from the header of the index.html after you install SASS. You will need to link it manually if you still want to use it. Open index.html and then add the following code inside the header. <link href = "css/style.css" rel = "stylesheet"> Almost every mobile app contains some fundamental elements. Usually those elements include a header and a footer that will cover the top and the bottom part of the screen. All the other elements will be placed between these two. Ionic provides ion-content element that serves as a container that will wrap all the other elements that we want to create. This container has some unique characteristics, but since this is a JavaScript based component which we will cover in the later part of this tutorial. <div class = "bar bar-header"> <h1 class = "title">Header</h1> </div> <div class = "list"> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> <div class = "bar bar-footer"> <h1 class = "title">Footer</h1> </div> The Ionic header bar is located on top of the screen. It can contain title, icons, buttons or some other elements on top of it. There are predefined classes of headers that you can use. You can check all of it in this tutorial. The main class for all the bars you might use in your app is bar. This class will always be applied to all the bars in your app. All bar subclasses will use the prefix – bar. If you want to create a header, you need to add bar-header after your main bar class. Open your www/index.html file and add the header class inside your body tag. We are adding a header to the index.html body because we want it to be available on every screen in the app. Since bar-header class has default (white) styling applied, we will add the title on top of it, so you can differentiate it from the rest of your screen. <div class = "bar bar-header"> <h1 class = "title">Header</h1> </div> The above code will produce the following screen − If you want to style your header, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as prefix to your color class. Since we are styling the header bar, the prefix class will be bar and the color class that we want to use in this example is positive (blue). <div class = "bar bar-header bar-positive"> <h1 class = "title">Header</h1> </div> The above code will produce the following screen − You can use any of the following nine classes to give a color of your choice to your app header − We can add other elements inside the header. The following code is an example to add a menu button and a home button inside a header. We will also add icons on top of our header buttons. <div class = "bar bar-header bar-positive"> <button class = "button icon ion-navicon"></button> <h1 class = "title">Header Buttons</h1> <button class = "button icon ion-home"></button> </div> The above code will produce the following screen − You can create a sub header that will be located just below the header bar. The following example will show how to add a header and a sub header to your app. Here, we have styled the sub header with an "assertive" (red) color class. <div class = "bar bar-header bar-positive"> <button class = "button icon ion-navicon"></button> <h1 class = "title">Header Buttons</h1> <button class = "button icon ion-home"></button> </div> <div class = "bar bar-subheader bar-assertive"> <h2 class = "title">Sub Header</h2> </div> The above code will produce the following screen − When your route is changed to any of the app screens, you will notice that the header and the sub header are covering some content as shown in the screenshot below. To fix this you need to add a ‘has-header’ or a ‘has-subheader’ class to the ion-content tags of your screens. Open one of your HTML files from www/templates and add the has-subheader class to the ion-content. If you only use header in your app, you will need to add the has-header class instead. <ion-content class = "padding has-subheader"> The above code will produce the following screen − Ionic footer is placed at the bottom of the app screen. Working with footers is almost the same as working with headers. The main class for Ionic footers is bar (the same as header). When you want to add footer to your screens, you need to add bar-footer class to your element after the main bar class. Since we want to use our footer on every screen in the app, we will add it to the body of the index.html file. We will also add title for our footer. <div class = "bar bar-footer"> <h1 class = "title">Footer</h1> </div> The above code will produce the following screen − If you want to style your footer, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as a prefix to your color class. Since we are styling a footer bar, the prefix class will be a bar and the color class that we want to use in this example is assertive (red). <div class = "bar bar-footer bar-assertive"> <h1 class = "title">Footer</h1> </div> The above code will produce the following screen − You can use any of the following nine classes to give a color of your choice to your app footer − Footers can contain elements inside it. Most of the time you will need to add buttons with icons inside a footer. The first button added will always be in the left corner. The last one will be placed on the right. The buttons in between will be grouped next to the first one on the left side of your footer. In following example, you can also notice that we use the icon class to add icons on top of the buttons. <div class = "bar bar-footer bar-assertive"> <button class = "button icon ion-navicon"></button> <button class = "button icon ion-home"></button> <button class = "button icon ion-star"></button> <button class = "button icon ion-checkmark-round"></button> </div> The above code will produce the following screen − If you want to move your button to the right you can add pull-right class. <div class = "bar bar-footer bar-assertive"> <button class = "button icon ion-navicon pull-right"></button> </div> The above code will produce the following screen − There are several types of buttons in the Ionic Framework and these buttons are subtly animated, which further enhances the user experience when using the app. The main class for all the button types is button. This class will always be applied to our buttons, and we will use it as a prefix when working with sub classes. Block buttons will always have 100% width of their parent container. They will also have a small padding applied. You will use button-block class for adding block buttons. If you want to remove padding but keep the full width, you can use the button-full class. Following is an example to show the usage of both classes − <button class = "button button-block"> button-block </button> <button class = "button button-full"> button-full </button> The above code will produce the following screen − There are two Ionic classes for changing the button size − button-small and button-small and button-large. button-large. Following is an example to show their usage − <button class = "button button-small"> button-small </button> <button class = "button button-large"> button-large </button> The above code will produce the following screen − If you want to style your button, you just need to add appropriate color class to it. When you style your elements, you need to add your main element class as a prefix to your color class. Since we are styling the footer bar, the prefix class will be a bar and the color class that we want to use in this example is assertive (red). <button class = "button button-assertive"> button-assertive </button> The above code will produce the following screen − You can use any of the following nine classes to give a color of your choice to your app buttons − If you want your buttons transparent, you can apply button-outline class. Buttons with this class will have an outline border and a transparent background. To remove the border from the button, you can use the button-clear class. The following example shows how to use these two classes. <button class = "button button-assertive button-outline"> button-outline </button> <button class = "button button-assertive button-clear"> button-clear </button> The above code will produce the following screen − When you want to add Icons to your buttons, the best way is to use the icon class. You can place the icon on one side of the button by using the icon-left or the icon-right. You will usually want to move your icon to one side when you have some text on top of your button as explained below. <button class = "button icon ion-home"> </button> <button class = "button icon icon-left ion-home"> Home </button> <button class = "button icon icon-right ion-home"> Home </button> The above code will produce the following screen − If you want to group a couple of buttons together, you can use the button-bar class. The buttons will have equal size by default. <div class = "button-bar"> <a class = "button button-positive">1</a> <a class = "button button-assertive">2</a> <a class = "button button-energized">3</a> <a class = "button">4</a> </div> The above code will produce the following screen − Lists are one of the most popular elements of any web or mobile application. They are usually used for displaying various information. They can be combined with other HTML elements to create different menus, tabs or to break the monotony of pure text files. Ionic framework offers different list types to make their usage easy. Every list is created with two elements. When you want to create a basic list your <ul> tag needs to have the list class assigned, and your <li> tag will use the item class. Another interesting thing is that you do not even need to use <ul>, <ol> and <li> tags for your lists. You can use any other elements, but the important thing is to add list and item classes appropriately. <div class = "list"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> </div> The above code will produce the following screen − When you need a list to fill your own container, you can add the list-insets after your list class. This will add some margin to it and it will adjust the list size to your container. <div class = "list list-inset"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> </div> The above code will produce the following screen − Dividers are used for organizing some elements into logical groups. Ionic gives us item-divider class for this. Again, like with all the other Ionic elements, we just need to add the item-divider class after the item class. Item dividers are useful as a list header, since they have stronger styling than the other list items by default. <div class = "list"> <div class = "item item-divider">Item Divider 1</div> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> <div class = "item item-divider">Item Divider 2</div> <div class = "item">Item 4</div> <div class = "item">Item 5</div> <div class = "item">Item 6</div> </div> The above code will produce the following screen − We already showed you how to add icons to your buttons. When adding icons to the list items, you need to choose what side you want to place them. There are item-icon-left and item-icon-right classes for this. You can also combine those two classes, if you want to have your Icons on both the sides. Finally, there is the item-note class to add a text note to your item. <div class = "list"> <div class = "item item-icon-left"> <i class = "icon ion-home"></i> Left side Icon </div> <div class = "item item-icon-right"> <i class = "icon ion-star"></i> Right side Icon </div> <div class = "item item-icon-left item-icon-right"> <i class = "icon ion-home"></i> <i class = "icon ion-star"></i> Both sides Icons </div> <div class = "item item-icon-left"> <i class = "icon ion-home"></i> <span class = "text-note">Text note</span> </div> </div> The above code will produce the following screen − Avatars and thumbnails are similar. The main difference is that avatars are smaller than thumbnails. These thumbnails are covering most of the full height of the list item, while avatars are medium sized circle images. The classes that are used are item-avatar and item-thumbnail. You can also choose which side you want to place your avatars and thumbnails as shown in the thumbnail code example below. <div class = "list"> <div class = "item item-avatar"> <img src = "my-image.png"> <h3>Avatar</h3> </div> <div class = "item item-thumbnail-left"> <img src = "my-image.png"> <h3>Thumbnail</h3> </div> </div> The above code will produce the following screen − Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In the previous chapter, we have discussed how to inset lists. Cards are very similar to inset lists, but they offer some additional shadowing that can influence the performance for larger lists. A default card can be created by adding a card class to your element. Cards are usually formed as lists with the item class. One of the most useful class is the item-text-wrap. This will help when you have too much text, so you want to wrap it inside your card. The first card in the following example does not have the item-text-wrap class assigned, but the second one is using it. <div class = "card"> <div class = "item"> This is a Ionic card without item-text-wrap class. </div> <div class = "item item-text-wrap"> This is a Ionic card with item-text-wrap class. </div> </div> The above code will produce the following screen − In the previous chapter, we have already discussed how to use the item-divider class for grouping lists. This class can be very useful when working with cards to create card headers. The same class can be used for footers as shown in the following code − <div class = "card list"> <div class = "item item-divider"> Card header </div> <div class = "item item-text-wrap"> Card text... </div> <div class = "item item-divider"> Card Footer </div> </div> The above code will produce the following screen − You can add any element on top of your card. In following example, we will show you how to use the full-image class together with the item-body to get a good-looking windowed image inside your card. <div class = "card"> <div class = "item item-avatar"> <img src = "my-image.png"> <h2>Card Name</h2> </div> <div class = "item item-body"> <img class = "full-image" src = "my-image.png"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. Nam tristique elit massa, quis faucibus augue finibus ac. </div> </div> The above code will produce the following screen − Ionic forms are mostly used for interaction with users and collecting needed info. This chapter will cover various text input forms and in our subsequent chapters, we will explain how to use other form elements using the Ionic framework. The best way to use forms is to use list and item as your main classes. Your app will usually consist more than one-form element, so it makes sense to organize it as a list. In the following example, you can notice that the item element is a label tag. You can use any other element, but a label will provide the ability to tap on any part of the element to focus your text input. You can set a placeholder that will look different from the input text and it will be hidden as soon as you start typing. You can see this in the example below. <div class = "list"> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> The above code will produce the following screen − Ionic offers some other options for your label. You can use the input-label class, if you want your placeholder to be on the left side when you type the text. <div class = "list"> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> The above code will produce the following screen − Stacked label is the other option that allows moving your label on top or the bottom of the input. To achieve this, we will add the item-stacked-label class to our label element and we need to create a new element and assign the input-label class to it. If we want it to be on top, we just need to add this element before the input tag. This is shown in the following example. Notice that the span tag is before the input tag. If we changed their places, it would appear below it on the screen. <div class = "list"> <label class = "item item-input item-stacked-label"> <span class = "input-label">Label 1</span> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input item-stacked-label"> <span class = "input-label">Label 2</span> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> The above code will produce the following screen − Floating labels are the third option we can use. These labels will be hidden before we start typing. As soon the typing starts, they will appear on top of the element with nice floating animation. We can use floating labels the same way as we used stacked labels. The only difference is that this time we will use item-floating-label class. <div class = "list"> <label class = "item item-input item-floating-label"> <span class = "input-label"t>Label 1</span> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input item-floating-label"> <span class = "input-label">Label 2</span> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> The above code will produce the following screen − In our last chapter, we discussed how to inset Ionic elements. You can also inset an input by adding the item-input-inset class to your item and the item-input-wrapper to your label. A Wrapper will add additional styling to your label. If you add some other elements next to your label, the label size will adjust to accommodate the new element. You can also add elements inside your label (usually icons). The following example shows two inset inputs. The first one has a button next to the label, and the second one has an icon inside it. We used the placeholder-icon class to make the icon with the same color as the placeholder text. Without it, the icon would use the color of the label. <div class = "list"> <div class = "item item-input-inset"> <label class = "item item-input-wrapper"> <input type = "text" placeholder = "Placeholder 1" /> </label> <button class = "button">button</button> </div> <div class = "item item-input-inset"> <label class = "item item-input-wrapper"> <i class = "icon ion-edit placeholder-icon"></i> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> </div> The above code will produce the following screen − Sometimes there are two options available for the users. The most efficient way to handle this situation is through toggle forms. Ionic gives us classes for toggle elements that are animated and easy to implement. Toggle can be implemented using two Ionic classes. First, we need to create a label for the same reason we explained in the previous chapter and assign a toggle class to it. Inside our label will be created . You will notice two more ionic classes used in the following example. The track class will add background styling to our checkbox and color animation when the toggle is tapped. The handle class is used to add a circle button to it. The following example shows two toggle forms. The first one is checked, the second one is not. <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> <br> <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> The above code will produce the following screen − Most of the time when you want to add more than one element of the same kind in Ionic, the best way is to use list items. The class that is used for multiple toggles is the item-toggle. The next example shows how to create a list for toggles. The first one and the second one are checked. <ul class = "list"> <li class = "item item-toggle"> Toggle 1 <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle 2 <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle 3 <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle 4 <label class = "toggle"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> </ul> The above code will produce the following screen − All the Ionic color classes can be applied to the toggle element. The Prefix will be the toggle. We will apply this to the label element. The following example shows all the colors that are applied. <ul class = "list"> <li class = "item item-toggle"> Toggle Light <label class = "toggle toggle-light"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Stable <label class = "toggle toggle-stable"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Positive <label class = "toggle toggle-positive"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Calm <label class = "toggle toggle-calm"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Balanced <label class = "toggle toggle-balanced"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Energized <label class = "toggle toggle-energized"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Assertive <label class = "toggle toggle-assertive"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Royal <label class = "toggle toggle-royal"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> <li class = "item item-toggle"> Toggle Dark <label class = "toggle toggle-dark"> <input type = "checkbox" /> <div class = "track"> <div class = "handle"></div> </div> </label> </li> </ul> The above code will produce the following screen − Ionic checkbox is almost the same as toggle. These two are styled differently but are used for the same purposes. When creating a checkbox form, you need to add the checkbox class name to both label and the input elements. The following example shows two simple checkboxes, one is checked and the other is not. <label class = "checkbox"> <input type = "checkbox"> </label> <label class = "checkbox"> <input type = "checkbox"> </label> The above code will produce the following screen − As we already showed, the list will be used for multiple elements. Now we will use the item-checkbox class for each list item. <ul class = "list"> <li class = "item item-checkbox"> Checkbox 1 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox"> Checkbox 2 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox"> Checkbox e <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox"> Checkbox 4 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> </ul> The above code will produce the following screen − When you want to style a checkbox, you need to apply any Ionic color class with the checkbox prefix. Check the following example to see how it looks like. We will use the list of checkboxes for this example. <ul class = "list"> <li class = "item item-checkbox checkbox-light"> Checkbox 1 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-stable"> Checkbox 2 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-positive"> Checkbox 3 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-calm"> Checkbox 4 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-balanced"> Checkbox 5 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-energized"> Checkbox 6 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-assertive"> Checkbox 7 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-royal"> Checkbox 8 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> <li class = "item item-checkbox checkbox-dark"> Checkbox 9 <label class = "checkbox"> <input type = "checkbox" /> </label> </li> </ul> The above code will produce the following screen − Radio buttons are another form of an element, which we will be covering in this chapter. The difference between radio buttons from toggle and checkbox forms is that when using the former, you choose only one radio button from the list. As the latter allows you to choose more than one. Since there will always be more than one radio button to choose from, the best way is to create a list. We did this whenever we wanted multiple elements. The list item class will be item-radio. Again, we will use label for this as we have used with all the other forms. Input will have the name attribute. This attribute will group all the buttons that you want to use as a possible choice. The item-content class is used to display options clearly. At the end, we will use the radio-icon class to add the checkmark icon that will be used to mark the option that the user chooses. In the following example, there are four radio buttons and the second one is chosen. <div class = "list"> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 1 </div> <i class = "radio-icon ion-checkmark"></i> </label> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 2 </div> <i class = "radio-icon ion-checkmark"></i> </label> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 3 </div> <i class = "radio-icon ion-checkmark"></i> </label> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 4 </div> <i class = "radio-icon ion-checkmark"></i> </label> </div> The above code will produce the following screen − Sometimes you want to create more than one group. This is what the name attribute is made for; the following example will group the first two and the last two buttons as two option groups. We will use the item-divider class to separate two groups. Notice that the first group has the name attribute equal to group1 and the second one uses group2. <div class = "list"> <div class = " item item-divider"> Group1 </div> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 1 </div> <i class = "radio-icon ion-checkmark"></i> </label> <label class = "item item-radio"> <input type = "radio" name = "group1" /> <div class = "item-content"> Choice 2 </div> <i class = "radio-icon ion-checkmark"></i> </label> <div class = "item item-divider"> Group2 </div> <label class = "item item-radio"> <input type = "radio" name = "group2" /> <div class = "item-content"> Choice 3 </div> <i class = "radio-icon ion-checkmark"></i> </label> <label class = "item item-radio"> <input type = "radio" name = "group2" /> <div class = "item-content"> Choice 4 </div> <i class = "radio-icon ion-checkmark"></i> </label> </div> The above code will produce the following screen − Ionic range is used to choose and display the level of something. It will represent the actual value in co-relation to maximal and minimal value. Ionic offers a simple way of working with Range. Range is used as an inside item element. The class that is used is range. We will place this class after the item class. This will prepare a container where the range will be placed. After creating a container, we need to add input and assign the range type to it and the name attribute as well. <div class = "item range"> <input type = "range" name = "range1"> </div> The above code will produce the following screen − Range will usually require icons to display the data clearly. We just need to add icons before and after the range input to place them on both sides of the range element. <div class = "item range"> <i class = "icon ion-volume-low"></i> <input type = "range" name = "volume"> <i class = "icon ion-volume-high"></i> </div> The above code will produce the following screen − Our next example will show you how to style Range with Ionic colors. The color classes will use a range prefix. We will create a list with nine ranges and style it differently. <div class = "list"> <div class = "item range range-light"> <input type = "range" name = "volume"> </div> <div class = "item range range-stable"> <input type = "range" name = "volume"> </div> <div class = "item range range-positive"> <input type = "range" name = "volume"> </div> <div class = "item range range-calm"> <input type = "range" name = "volume"> </div> <div class = "item range range-balanced"> <input type = "range" name = "volume"> </div> <div class = "item range range-energized"> <input type = "range" name = "volume"> </div> <div class = "item range range-assertive"> <input type = "range" name = "volume"> </div> <div class = "item range range-royal"> <input type = "range" name = "volume"> </div> <div class = "item range range-dark"> <input type = "range" name = "volume"> </div> </div> The above code will produce the following screen − Ionic Select will create a simple menu with select options for the user to choose. This Select Menu will look differently on different platforms, since its styling is handled by the browser. First, we will create a label and add the item-input and the item-select classes. The second class will add additional styling to the select form and then we will add the input-label class inside that will be used to add a name to our select element. We will also add select with option inside. This is regular HTML5 select element. The following example is showing Ionic Select with three options. <label class = "item item-input item-select"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> The above code will produce the following screen − The following example will show you how to apply styling to select. We are creating a list with nine differently styled select elements using Ionic colors. Since we are using list with items, item will be the prefix to the color classes. <div class = "list"> <label class = "item item-input item-select item-light"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-stable"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-positive"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-calm"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-balanced"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-energized"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-assertive"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-royal"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-dark"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> </div> The above code will produce the following screen − Ionic tabs are most of the time used for mobile navigation. Styling is optimized for different platforms. This means that on android devices, tabs will be placed at the top of the screen, while on IOS it will be at the bottom. There are different ways of creating tabs. We will understand in detail, how to create tabs in this chapter. Simple Tabs menu can be created with a tabs class. For the inside element that is using this class, we need to add tab-item elements. Since tabs are usually used for navigation, we will use <a> tags for tab items. The following example is showing a menu with four tabs. <div class = "tabs"> <a class = "tab-item"> Tab 1 </a> <a class = "tab-item"> Tab 2 </a> <a class = "tab-item"> Tab 3 </a> </div> The above code will produce the following screen − Ionic provides classes for adding icons to tabs. If you want your tabs to have icons without any text, a tabs-icon-only class should be added after the tabs class. Of course, you need to add icons you want to display. <div class = "tabs tabs-icon-only"> <a class = "tab-item"> <i class = "icon ion-home"></i> </a> <a class = "tab-item"> <i class = "icon ion-star"></i> </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> </a> </div> The above code will produce the following screen − You can also add icons and text together. The tabs-icon-top and tabs-icon-left are classes that will place the icon above or on the left side respectively. Implementation is the same as the example given above, we will just add a new class and text that we want to use. The following example shows icons placed above the text. <div class = "tabs tabs-icon-top"> <a class = "tab-item"> <i class = "icon ion-home"></i> Tab 1 </a> <a class = "tab-item"> <i class = "icon ion-star"></i> Tab 2 </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> Tab 3 </a> </div> The above code will produce the following screen − Striped Tabs can be created by adding a container around our tabs with the tabs-striped class. This class allows the usage of the tabs-background and the tabs-color prefixes for adding some of the Ionic colors to the tabs menu. In the following example, we will use the tabs-background-positive (blue) class to style the background of our menu, and the tabs-color-light (white) class to style the tab icons. Notice the difference between the second tab that is active and the other two that are not. <div class = "tabs-striped tabs-background-positive tabs-color-light"> <div class = "tabs"> <a class = "tab-item"> <i class = "icon ion-home"></i> </a> <a class = "tab-item active"> <i class = "icon ion-star"></i> </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> </a> </div> </div> The above code will produce the following screen − Working with the Ionic Grid System is straightforward. There are two main classes – row for working with rows and col for columns. You can choose as many columns or rows you want. All of them will adjust its size to accommodate the available space, although you can change this behavior to suit your needs. NOTE − All examples in this tutorial will have borders applied to our grid to be able to display it in a way that is easy to understand. The following example shows how to use the col and the row classes. We will create two rows. The first row will have five columns and the second one will have only three. Notice how the width of the columns is different in the first and second row. <div class = "row"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div> The above code will produce the following screen − Sometimes you do not want to leave the column sizes automatically assigned. If this is the case, you can choose the col prefix followed by a number that will represent a percentage of the row width. This will apply only to the column with a specific size applied. The other columns will adjust to the available space that is left. In the following example, the first column will use 50 percent of the full width and the others will adjust accordingly. <div class = "row"> <div class = "col col-50">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col col-50">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div> The above code will produce following screen − The following table shows the available percentage options that Ionic grid system provides − The columns can be offset from the left. It works the same for the specific size of the columns. This time the prefix will be col-offset and then we will use the same percentage numbers showed in the table above. The following example shows how can we offset the second column of both the rows by 25 percent. <div class = "row"> <div class = "col">col 1</div> <div class = "col col-offset-25">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col">col 1</div> <div class = "col col-offset-25">col 2</div> <div class = "col">col 3</div> </div> The above code will produce the following screen − You can also vertically align the columns inside a row. There are three classes, which can be used, namely – top, center and the bottom class with the col prefix. The following code shows how to place vertically the first three columns of both rows. NOTE − In the example that follows we added “.col {height: 120px}” to our CSS to show you the vertical placing of the columns. <div class = "row"> <div class = "col col-top">col 1</div> <div class = "col col-center">col 2</div> <div class = "col col-bottom">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col col-top">col 1</div> <div class = "col col-center">col 2</div> <div class = "col col-bottom">col 3</div> </div> The above code will produce the following screen − The Ionic Grid can also be used for a responsive layout. There are three classes available. The responsive-sm class will collapse columns into a single row when the viewport is smaller than a landscape phone. The responsive-md class will be applied when viewport is smaller than a portrait tablet. The responsive-lg class will be applied when viewport is smaller than a landscape tablet. The first image after the following example shows how the responsive-sm class looks on a Mobile device and the second one shows how the same responsive grid looks differently on a Tablet device. <div class = "row responsive-sm"> <div class = "col col-25">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row responsive-sm"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div> There are more than 700 premium icons provided by Ionic. There are also different sets of icons provided for Android and IOS. You can find almost anything you need but you are not bound to use them, if you do not want to. You can use your own custom icons or any other icon set instead. You can check all the Ionic icons here. If you want to use Ionic icons find the icon you need on the page (https://ionicons.com/). When you are adding Ionic elements, you always add the main class first and then you add the subclass you want. The main class for all icons is icon. The Subclass is the name of the icon you want. We will add six icons in our example that is given below − <i class = "icon icon ion-happy-outline"></i> <i class = "icon icon ion-star"></i> <i class = "icon icon ion-compass"></i> <i class = "icon icon ion-planet"></i> <i class = "icon icon ion-ios-analytics"></i> <i class = "icon icon ion-ios-eye"></i> The above code will produce the following screen − The size of these icons can be changed with the font-size property in your Ionic CSS file. .icon { font-size: 50px; } Once the icon size is setup, the same code will produce the following screenshot as the output − Ionic offers an easy way to add padding to elements. There are couple of classes that can be used and all of them will add 10px between border of element and its content. The following table displays all the available padding classes. When you want to apply some padding to your element, you just need to assign one of the classes from the table above. The following example shows two block buttons. The first one is using the padding class and the second one does not. You will notice that the first button is larger, since it has 10px padding applied. <div class = "button button-block padding">Padding</div> <div class = "button button-block">No padding</div> The above code will produce the following screen − The Action Sheet is an Ionic service that will trigger a slide up pane on the bottom of the screen, which you can use for various purposes. In the following example, we will show you how to use the Ionic action sheet. First we will inject $ionicActionSheet service as a dependency to our controller, then we will create $scope.showActionSheet() function, and lastly we will create a button in our HTML template to call the function we created. .controller('myCtrl', function($scope, $ionicActionSheet) { $scope.triggerActionSheet = function() { // Show the action sheet var showActionSheet = $ionicActionSheet.show({ buttons: [ { text: 'Edit 1' }, { text: 'Edit 2' } ], destructiveText: 'Delete', titleText: 'Action Sheet', cancelText: 'Cancel', cancel: function() { // add cancel code... }, buttonClicked: function(index) { if(index === 0) { // add edit 1 code } if(index === 1) { // add edit 2 code } }, destructiveButtonClicked: function() { // add delete code.. } }); }; }) <button class = "button">Action Sheet Button</button> When we tap the button, it will trigger the $ionicActionSheet.show function and the Action Sheet will appear. You can create your own functions that will be called when one of the options is taped. The cancel function will close the pane, but you can add some other behavior, which will be called when the cancel option is tapped before the pane is closed. The buttonClicked function is the place where you can write the code that will be called when one of the edit options is tapped. We can keep track of multiple buttons by using the index parameter. The destructiveButtonCLicked is a function that will be triggered when the delete option is tapped. This option is red by default. The $ionicActionSheet.show() method has some other useful parameters. You can check all of them in the following table. The Ionic Backdrop will overlay the content of the screen when applied. It will appear below other overlays (popup, loading, etc...). There are two methods that can be used for managing backdrop service. The $ionicBackdrop.retain() will apply backdrop over the components, and $ionicBackdrop.release() will remove it. The following example shows how to use backdrop. We are adding $ionicBackdrop as a dependency to the controller, then creating the $scope.showBackdrop() function that will call the retain method immediately. Then, after three seconds, it will call the release method. We are using $timeout for the release method, so we need to add it as a controller dependency too. .controller('myCtrl', function($scope, $ionicBackdrop, $timeout) { $scope.showBackdrop = function() { $ionicBackdrop.retain(); $timeout(function() { $ionicBackdrop.release(); }, 3000); }; }) You will notice how the screen is darker in the following image, since the backdrop is applied. Almost every mobile app contains some fundamental elements. Usually these elements include a header and a footer, which will cover the top and the bottom part of the screen. All the other elements will be placed between these two. Ionic provide ion-content element that serves as a container, which will wrap all the other elements that we want to create. Let us consider the following example − <div class = "bar bar-header"> <h1 class = "title">Header</h1> </div> <div class = "list"> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 1" /> </label> <label class = "item item-input"> <input type = "text" placeholder = "Placeholder 2" /> </label> </div> <div class = "bar bar-footer"> <h1 class = "title">Footer</h1> </div> In this chapter, we will understand what JavaScript forms are and will learn what a JavaScript checkbox, radio buttons and toggle are. Let us see how to use the Ionic JavaScript checkbox. Firstly, we need to create an ion-checkbox element in the HTML file. Inside this, we will assign an ng-model attribute that will be connected to the angular $scope. You will notice that we are using a dot when defining the value of a model even though it would work without it. This will allow us to keep the link between the child and the parent scopes at all times. This is very important as it helps to avoid some issues that could happen in the future. After we create the element, we will bind its value using angular expressions. <ion-checkbox ng-model = "checkboxModel.value1">Checkbox 1</ion-checkbox> <ion-checkbox ng-model = "checkboxModel.value2">Checkbox 2</ion-checkbox> <p>Checkbox 1 value is: <b>{{checkboxModel.value1}}</b></p> <p>Checkbox 2 value is: <b>{{checkboxModel.value2}}</b></p> Next, we need to assign values to our model inside the controller. The values we will use are false, since we want to start with unchecked checkboxes. $scope.checkboxModel = { value1 : false, value2 : false }; The above code will produce the following screen − Now, when we tap the checkbox elements, it will automatically change their model value to “true” as shown in the following screenshot. To start with, we should create three ion-radio elements in our HTML and assign the ng-model and the ng-value to it. After that, we will display the chosen value with angular expression. We will start by unchecking all the three radioelements, so the value will not be assigned to our screen. <ion-radio ng-model = "radioModel.value" ng-value = "1">Radio 1</ion-radio> <ion-radio ng-model = "radioModel.value" ng-value = "2">Radio 2</ion-radio> <ion-radio ng-model = "radioModel.value" ng-value = "3">Radio 3</ion-radio> <p>Radio value is: <b>{{radioModel.value}}</b></p> The above code will produce the following screen − When we tap on the second checkbox element, the value will change accordingly. You will notice that toggle is similar to checkbox. We will follow the same steps as we did with our checkbox. In the HTML file, first we will create ion-toggle elements, then assign the ng-model value and then bind expression values of to our view. <ion-toggle ng-model = "toggleModel.value1">Toggle 1</ion-toggle> <ion-toggle ng-model = "toggleModel.value2">Toggle 2</ion-toggle> <ion-toggle ng-model = "toggleModel.value3">Toggle 3</ion-toggle> <p>Toggle value 1 is: <b>{{toggleModel.value1}}</b></p> <p>Toggle value 2 is: <b>{{toggleModel.value2}}</b></p> <p>Toggle value 3 is: <b>{{toggleModel.value3}}</b></p> Next, we will assign values to $scope.toggleModel in our controller. Since, toggle uses Boolean values, we will assign true to the first element and false to the other two. $scope.toggleModel = { value1 : true, value2 : false, value3 : false }; The above code will produce the following screen − Now we will tap on second and third toggle to show you how the values change from false to true. Various Ionic events can be used to add interactivity with users. The following table explains all the Ionic events. Since all the Ionic events can be used the same way, we will show you how to use the on-touch event and you can just apply the same principles to the other events. To start with, we will create a button and assign an on-touch event, which will call the onTouchFunction(). <button on-touch = "onTouchFunction()" class="button">Test</button> Then we will create that function in our controller scope. $scope.onTouchFunction = function() { // Do something... } Now, when touch event occurs the onTouchFunction() will be called. This is the Ionic directive, which will add the header bar. To create a JavaScript header bar, we need to apply the ion-header-bar directive in the HTML file. Since the default header is white, we will add title, so it will be showed on white background. We will add it to our index.html file. <ion-header-bar> <h1 class = "title">Title!</h1> </ion-header-bar> The above code will produce the following screen − Just like the CSS Header Bar, the JavaScript counterpart can be styled in a similar fashion. To apply color, we need to add a color class with a bar prefix. Therefore, if we want to use a blue header, we will add a bar-positive class. We can also move the title to one side of the screen by adding the align-title attribute. The values for this attribute can be center, left or right. <ion-header-bar align-title = "left" class = "bar-positive"> <h1 class = "title">Title!</h1> </ion-header-bar> The above code will produce the following screen − You will usually want to add some elements to your header. The following example shows how to place a button on the left side and an icon to the right side of the ion-header-bar. You can also add other elements to your header. <ion-header-bar class = "bar-positive"> <div class = "buttons"> <button class = "button">Button</button> </div> <h1 class = "title">Title!</h1> <div class = "buttons"> <button class = "button icon ion-home"></button> </div> </ion-header-bar> The above code will produce the following screen − A Sub header is created when a bar-subheader class is added to the ion-header-bar. We will add a bar-assertive class to apply red color to our sub header. <ion-header-bar class = "bar-positive"> <div class = "buttons"> <button class = "button">Button</button> </div> <h1 class = "title">Title!</h1> <div class = "buttons"> <button class = "button icon ion-home"></button> </div> </ion-header-bar> <ion-header-bar class = "bar-subheader bar-assertive"> <h1 class = "title">Subheader</h1> </ion-header-bar> The above code will produce the following screen − This directive will add a footer bar at the bottom of the screen. The Ionic footer can be added by applying an ion-footer-bar class. Working with it is same as working with header. We can add a title and place it on the left, center or right side of the screen by using the align-title attribute. With the prefix bar, we can use the Ionic colors. Let us create a red colored footer with the title in the center. <ion-footer-bar align-title = "center" class = "bar-assertive"> <h1 class = "title">Title!</h1> </ion-footer-bar> The above code will produce the following screen − We can add buttons icons or other elements to the ion-footer-bar and their styling will be applied. Let us add a button and an Icon to our footer. <ion-footer-bar class = "bar-assertive"> <div class = "buttons"> <button class = "button">Button</button> </div> <h1 class = "title">Footer</h1> <div class = "buttons"> <button class = "button icon ion-home"></button> </div> </ion-footer-bar> The above code will produce the following screen− We showed you how to use a sub header. The same way a sub footer can be created. It will be located above the footer bar. All we need to do is add a bar-subfooter class to our ion-footer-bar element. In example that follows, we will add the sub-footer above the footer bar, which we previously created. <ion-footer-bar class = "bar-subfooter bar-positive"> <h1 class = "title">Sub Footer</h1> </ion-footer-bar> <ion-footer-bar class = "bar-assertive"> <div class = "buttons"> <button class = "button">Button</button> </div> <h1 class = "title">Footer</h1> <div class = "buttons" ng-click = "doSomething()"> <button class = "button icon ion-home"></button> </div> </ion-footer-bar> The above code will produce the following screen − Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open the keyboard. There are some functionalities, which the developers can adjust while working with the Ionic keyboard. When you want to hide some elements while the keyboard is open, you can use the hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when the keyboard is open. <label class = "item item-input"> <input type = "text" placeholder = "Input 1"> </label> <button class = "button button-block hide-on-keyboard-open"> button </button> The above code will produce the following screen − Now, when we tap on the input field, the keyboard will open automatically and the button will become hidden. A nice feature of Ionic is that it will adjust elements on screen, so the focused element is always visible when the keyboard is open. The following image below shows ten Input forms and the last one is blue. When we tap the blue form, Ionic will adjust our screen, so the blue form is always visible. Note − This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates, you will notice that all templates use ion-content directive as a container to other screen elements, so the Scroll View is always applied. We already discussed Ionic CSS list elements in the previous chapters. In this chapter, we will show you JavaScript lists. They allow us to use some new features like swipe, drag and remove. The directives used for displaying lists and items are ion-list and ion-item as shown below. <ion-list> <ion-item> Item 1 </ion-item> <ion-item> Item 2 </ion-item> <ion-item> Item 3 </ion-item> </ion-list> The above code will produce the following screen − This button can be added by using the ion-delete-button directive. You can use any icon class you want. Since we do not always want to show the delete buttons, because users might accidentally tap it and trigger the delete process, we can add the show-delete attribute to the ion-list and connect it with the ng-model. In the following example, we will use the ion-toggle as a model. When the toggle is on delete, the buttons will appear on our list items. <ion-list show-delete = "showDelete1"> <ion-item> <ion-delete-button class = "ion-minus-circled"></ion-delete-button> Item 1 </ion-item> <ion-item> <ion-delete-button class = "ion-minus-circled"></ion-delete-button> Item 2 </ion-item> </ion-list> <ion-toggle ng-model = "showDelete2"> Show Delete 2 </ion-toggle> The above code will produce the following screen − The Ionic directive for the reorder button is ion-reorder-button. The element we created has an on-reorder attribute that will trigger the function from our controller whenever the user is dragging this element. <ion-list show-reorder = "true"> <ion-item ng-repeat = "item in items"> Item {{item.id}} <ion-reorder-button class = "ion-navicon" on-reorder = "moveItem(item, $fromIndex, $toIndex)"></ion-reorder-button> </ion-item> </ion-list> $scope.items = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ]; $scope.moveItem = function(item, fromIndex, toIndex) { $scope.items.splice(fromIndex, 1); $scope.items.splice(toIndex, 0, item); }; The above code will produce the following screen − When we click the icon on the right, we can drag the element and move it to some other place in the list. The Option button is created using an ion-option-button directive. These buttons are showed when the list item is swiped to the left and we can hide it again by swiping the item element to the right. You can see in the following example that there are two buttons, which are hidden. <ion-list> <ion-item> Item with two buttons... <ion-option-button class = "button-positive">Button 1</ion-option-button> <ion-option-button class = "button-assertive">Button 2</ion-option-button> </ion-item> </ion-list> The above code will produce the following screen − When we swipe the item element to the left, the text will be moved left and buttons will appear on the right side. The collection-repeat function is an updated version of the AngularJS ng-repeat directive. It will only render visible elements on the screen and the rest will be updated as you scroll. This is an important performance improvement when you are working with large lists. This directive can be combined with item-width and item-height attributes for further optimization of the list items. There are some other useful attributes for working with images inside your list. The item-render-buffer function represents number of items that are loaded after visible items. The higher this value, the more items will be preloaded. The force-refresh-images function will fix an issue with source of the images while scrolling. Both of these classes will influence the performance in a negative way. Ionic loading will disable any interaction with users when showed and enable it again when it is needed. Loading is triggered inside the controller. First, we need to inject $ionicLoading in our controller as dependency. After that, we need to call the $ionicLoading.show() method and loading will appear. For disabling it, there is a $ionicLoading.hide() method. .controller('myCtrl', function($scope, $ionicLoading) { $scope.showLoading = function() { $ionicLoading.show({ template: 'Loading...' }); }; $scope.hideLoading = function(){ $ionicLoading.hide(); }; }); <button class = "button button-block" ng-click = "showLoading()"></button> When a user taps the button, the loading will appear. You will usually want to hide the loading after some time consuming functionalities are finished. Some other option parameters can be used when working with loading. The explanation is shown in the table below. Ionic config is used to configure options you want to be used in all of the $ionicLoading services throughout the app. This can be done by using $ionicLoadingConfig. Since constants should be added to the main app module, open your app.js file and add your constant after module declaration. .constant('$ionicLoadingConfig', { template: 'Default Loading Template...' }) The above code will produce the following screen − When Ionic modal is activated, the content pane will appear on top of the regular content. Modal is basically larger popup with more functionalities. Modal will cover entire screen by default but it can be optimized the way you want. There are a two ways of implementing modal in Ionic. One way is to add separate template and the other is to add it on top of the regular HTML file, inside the script tags. The first thing we need to do is to connect our modal to our controller using angular dependency injection. Then we need to create a modal. We will pass in scope and add animation to our modal. After that, we will create functions for opening, closing, destroying modal. The last two functions are placed where we can write the code that will be triggered if a modal is hidden or removed. If you do not want to trigger any functionality, when the modal is removed or hidden, you can delete the last two functions. .controller('MyController', function($scope, $ionicModal) { $ionicModal.fromTemplateUrl('my-modal.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; }); $scope.openModal = function() { $scope.modal.show(); }; $scope.closeModal = function() { $scope.modal.hide(); }; //Cleanup the modal when we're done with it! $scope.$on('$destroy', function() { $scope.modal.remove(); }); // Execute action on hide modal $scope.$on('modal.hidden', function() { // Execute action }); // Execute action on remove modal $scope.$on('modal.removed', function() { // Execute action }); }); <script id = "my-modal.html" type = "text/ng-template"> <ion-modal-view> <ion-header-bar> <h1 class = "title">Modal Title</h1> </ion-header-bar> <ion-content> <button class = "button icon icon-left ion-ios-close-outline" ng-click = "closeModal()">Close Modal</button> </ion-content> </ion-modal-view> </script> The way we showed in the last example is when the script tag is used as a container to our modal inside some existing HTML file. The second way is to create a new template file inside the templates folder. We will use the same code as in our last example, but we will remove the script tags and we also need to change fromTemplateUrl in controller to connect modal with new created template. .controller('MyController', function($scope, $ionicModal) { $ionicModal.fromTemplateUrl('templates/modal-template.html', { scope: $scope, animation: 'slide-in-up', }).then(function(modal) { $scope.modal = modal; }); $scope.openModal = function() { $scope.modal.show(); }; $scope.closeModal = function() { $scope.modal.hide(); }; //Cleanup the modal when we're done with it! $scope.$on('$destroy', function() { $scope.modal.remove(); }); // Execute action on hide modal $scope.$on('modal.hidden', function() { // Execute action }); // Execute action on remove modal $scope.$on('modal.removed', function() { // Execute action }); }); <ion-modal-view> <ion-header-bar> <h1 class = "title">Modal Title</h1> </ion-header-bar> <ion-content> <button class = "button icon icon-left ion-ios-close-outline" ng-click = "closeModal()">Close Modal</button> </ion-content> </ion-modal-view> The third way of using Ionic modal is by inserting HTML inline. We will use the fromTemplate function instead of the fromTemplateUrl. .controller('MyController', function($scope, $ionicModal) { $scope.modal = $ionicModal.fromTemplate( '<ion-modal-view>' + ' <ion-header-bar>' + '<h1 class = "title">Modal Title</h1>' + '</ion-header-bar>' + '<ion-content>'+ '<button class = "button icon icon-left ion-ios-close-outline" ng-click = "closeModal()">Close Modal</button>' + '</ion-content>' + '</ion-modal-view>', { scope: $scope, animation: 'slide-in-up' }) $scope.openModal = function() { $scope.modal.show(); }; $scope.closeModal = function() { $scope.modal.hide(); }; //Cleanup the modal when we're done with it! $scope.$on('$destroy', function() { $scope.modal.remove(); }); // Execute action on hide modal $scope.$on('modal.hidden', function() { // Execute action }); // Execute action on remove modal $scope.$on('modal.removed', function() { // Execute action }); }); All three examples will have the same effect. We will create a button to trigger the $ionicModal.show() to open modal. <button class = "button" ng-click = "openModal()"></button> When we open modal, it will contain a button that will be used for closing it. We created this button in a HTML template. There are also other options for modal optimization. We already showed how to use scope and animation. The following table shows other options. Navigation is one of the core components of every app. Ionic is using the AngularJS UI Router for handling the navigation. Navigation can be configured in the app.js file. If you are using one of the Ionic templates, you will notice the $stateProvider service injected into the app config. The simplest way of creating states for the app is showed in the following example. The $stateProvider service will scan the URL, find the corresponding state and load the file, which we defined in app.config. .config(function($stateProvider) { $stateProvider .state('index', { url: '/', templateUrl: 'templates/home.html'}) .state('state1', {url: '/state1', templateUrl: 'templates/state1.html'}) .state('state2', {url: '/state2', templateUrl: 'templates/state2.html',}); }); The state will be loaded into the ion-nav-view element, which can be placed in the index.html body. <ion-nav-view></ion-nav-view> When we created states in the above-mentioned example, we were using the templateUrl, so when the state is loaded, it will search for matching the template file. Now, we will open the templates folder and create a new file state1.html, which will be loaded when the app URL is changed to /state1. state1.html Code <ion-view> <ion-content> This is State 1 !!! </ion-content> </ion-view> You can add a navigation bar to your app in the index.html body by adding the “ion-nav-bar” element. Inside the navigation bar, we will add the ion-nav-back-button with an icon. This will be used for returning to the previous state. The button will appear automatically when the state is changed. We will assign the goBack() function, which will use the $ionicHistory service for handling this functionality. Therefore, when the user leaves the home state and goes to state1, the back button will appear which can be taped, if the user wants to return to the home state. <ion-nav-bar class = "bar-positive"> <ion-nav-back-button class = "button-clear" ng-click = "goBack()"> <i class = "icon ion-arrow-left-c"></i> Back </ion-nav-back-button> </ion-nav-bar> .MyCtrl($scope, $ionicHistory) { $scope.goBack = function() { $ionicHistory.goBack(); }; } Buttons can be added to the navigation bar using the ion-nav-buttons. This element should be placed inside the ion-nav-bar or the ion-view. We can assign the side attribute with four option values. The primary and secondary values will place buttons according to the platform that is used. Sometimes you want the buttons on one side no matter if it is IOS or Android. If that is the case, you can use the left or the right attributes instead. We can also add the ion-nav-title to the navigation bar. All the code will be placed in the index.html body, so it can be used everywhere. <ion-nav-bar class = "bar-positive"> <ion-nav-title> Title </ion-nav-title> <ion-nav-buttons side = "primary"> <button class = "button"> Button 1 </button> </ion-nav-buttons> </ion-nav-bar> It will produce the following screen − The following table shows a few other functionalities, which can be used with Ionic navigation. Ionic has the ability for caching up to ten views to improve performance. It also offers a way to handle caching manually. Since only backward views are cached and the forward ones are loading each time the users visit them, we can easily set to cache forward views by using following the code. $ionicCinfigProvider.views.forwardCache(true); We can also set how many states should be cached. If we want three views to be cached, we can use the following code. $ionicConfigProvider.views.maxCache(3); Caching can be disabled inside $stateProvider or by setting attribute to ion-view. Both examples are below. $stateProvider.state('state1', { cache: false, url : '/state1', templateUrl: 'templates/state1.html' }) <ion-view cache-view = "false"></ion-view> We can control the behavior of the navigation bar by using the $ionicNavBarDelegate service. This service needs to be injected to our controller. <ion-nav-bar> <button ng-click = "setNavTitle('title')"> Set title to banana! </button> </ion-nav-bar> $scope.setNavTitle = function(title) { $ionicNavBarDelegate.title(title); } The $ionicNavBarDelegate service has other useful methods. Some of these methods are listed in the following table. You can track the history of the previous, current and the forward views by using the $ionicHistory service. The following table shows all the methods of this service. The nextViewOptions() method has the following three options available. disableAnimate is used for disabling animation of the next view change. disableAnimate is used for disabling animation of the next view change. disableBack will set the back view to null. disableBack will set the back view to null. historyRoot will set the next view as the root view. historyRoot will set the next view as the root view. $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); This is a view that will appear above the regular view. A Popover can be created by using ion-popover-view element. This element should be added to the HTML template and the $ionicPopover service needs to be injected into the controller. There are three ways of adding popover. The first one is the fromTemplate method, which allows using the inline template. The second and the third way of adding popover is to use the fromTemplateUrl method. Let us understand the fromtemplate method as explained below. .controller('DashCtrl', function($scope, $ionicLoading, $ionicPopover) { // .fromTemplate() method var template = '<ion-popover-view>' + '<ion-header-bar>' + '<h1 class = "title">Popover Title</h1>' + '</ion-header-bar>'+ '<ion-content>' + 'Popover Content!' + '</ion-content>' + '</ion-popover-view>'; $scope.popover = $ionicPopover.fromTemplate(template, { scope: $scope }); $scope.openPopover = function($event) { $scope.popover.show($event); }; $scope.closePopover = function() { $scope.popover.hide(); }; //Cleanup the popover when we're done with it! $scope.$on('$destroy', function() { $scope.popover.remove(); }); // Execute action on hide popover $scope.$on('popover.hidden', function() { // Execute action }); // Execute action on remove popover $scope.$on('popover.removed', function() { // Execute action }); }) As discussed above, the second and the third way of adding popover is to use fromTemplateUrl method. The controller code will be the same for both ways except the fromTemplateUrl value. If the HTML is added to an existing template, the URL will be the popover.html. If we want to place the HTML into the templates folder, then the URL will change to templates/popover.html. Both examples have been explained below. .controller('MyCtrl', function($scope, $ionicPopover) { $ionicPopover.fromTemplateUrl('popover.html', { scope: $scope }).then(function(popover) { $scope.popover = popover; }); $scope.openPopover = function($event) { $scope.popover.show($event); }; $scope.closePopover = function() { $scope.popover.hide(); }; //Cleanup the popover when we're done with it! $scope.$on('$destroy', function() { $scope.popover.remove(); }); // Execute action on hide popover $scope.$on('popover.hidden', function() { // Execute action }); // Execute action on remove popover $scope.$on('popover.removed', function() { // Execute action }); }) Now, we will add the script with template to the HTML file, which we are using for calling the popover function. <script id = "popover.html" type = "text/ng-template"> <ion-popover-view> <ion-header-bar> <h1 class = "title">Popover Title</h1> </ion-header-bar> <ion-content> Popover Content! </ion-content> </ion-popover-view> </script> If we want to create an HTML as a separate file, we can create a new HTML file in the templates folder and use the same code as we used in the above-mentioned example without the script tags. The newly created HTML file is as follows. <ion-popover-view> <ion-header-bar> <h1 class = "title">Popover Title</h1> </ion-header-bar> <ion-content> Popover Content! </ion-content> </ion-popover-view> The last thing we need is to create a button that will be clicked to show the popover. <button class = "button" ng-click = "openPopover($event)">Add Popover</button> Whatever way we choose from above examples, the output will always be the same. The following table shows the $ionicPopover methods that can be used. This service is used for creating a popup window on top of the regular view, which will be used for interaction with the users. There are four types of popups namely − show, confirm, alert and prompt. This popup is the most complex of all. To trigger popups, we need to inject the $ionicPopup service to our controller and then just add a method that will trigger the popup we want to use, in this case $ionicPopup.show(). The onTap(e) function can be used for adding e.preventDefault() method, which will keep the popup open, if there is no change applied to the input. When the popup is closed, the promised object will be resolved. .controller('MyCtrl', function($scope, $ionicPopup) { // When button is clicked, the popup will be shown... $scope.showPopup = function() { $scope.data = {} // Custom popup var myPopup = $ionicPopup.show({ template: '<input type = "text" ng-model = "data.model">', title: 'Title', subTitle: 'Subtitle', scope: $scope, buttons: [ { text: 'Cancel' }, { text: '<b>Save</b>', type: 'button-positive', onTap: function(e) { if (!$scope.data.model) { //don't allow the user to close unless he enters model... e.preventDefault(); } else { return $scope.data.model; } } } ] }); myPopup.then(function(res) { console.log('Tapped!', res); }); }; }) <button class = "button" ng-click = "showPopup()">Add Popup Show</button> You probably noticed in the above-mentioned example some new options were used. The following table will explain all of those options and their use case. A Confirm Popup is the simpler version of Ionic popup. It contains Cancel and OK buttons that users can press to trigger the corresponding functionality. It returns the promised object that is resolved when one of the buttons are pressed. .controller('MyCtrl', function($scope, $ionicPopup) { // When button is clicked, the popup will be shown... $scope.showConfirm = function() { var confirmPopup = $ionicPopup.confirm({ title: 'Title', template: 'Are you sure?' }); confirmPopup.then(function(res) { if(res) { console.log('Sure!'); } else { console.log('Not sure!'); } }); }; }) <button class = "button" ng-click = "showConfirm()">Add Popup Confirm</button> The following table explains the options that can be used for this popup. An Alert is a simple popup that is used for displaying the alert information to the user. It has only one button that is used to close the popup and resolve the popups’ promised object. .controller('MyCtrl', function($scope, $ionicPopup) { $scope.showAlert = function() { var alertPopup = $ionicPopup.alert({ title: 'Title', template: 'Alert message' }); alertPopup.then(function(res) { // Custom functionality.... }); }; }) <button class = "button" ng-click = "showAlert()">Add Popup Alert</button> It will produce the following screen − The following table shows the options that can be used for an alert popup. The last Ionic popup that can be created using Ionic is prompt. It has an OK button that resolves promise with value from the input and Cancel button that resolves with undefined value. .controller('MyCtrl', function($scope, $ionicPopup) { $scope.showPrompt = function() { var promptPopup = $ionicPopup.prompt({ title: 'Title', template: 'Template text', inputType: 'text', inputPlaceholder: 'Placeholder' }); promptPopup.then(function(res) { console.log(res); }); }; }) <button class = "button" ng-click = "showPrompt()">Add Popup Prompt</button> It will produce the following screen − The following table shows options that can be used for a prompt popup. The element used for scrolling manipulation in ionic apps is called as the ion-scroll. The following code snippets will create scrollable containers and adjust scrolling patterns. First, we will create our HTML element and add properties to it. We will add → direction = "xy" to allow scrolling to every side. We will also set the width and the height for the scroll element. <ion-scroll zooming = "true" direction = "xy" style = "width: 320px; height: 500px"> <div class = "scroll-container"></div> </ion-scroll> Next, we will add the image of our world map to div element, which we created inside the ion-scroll and set its width and height. .scroll-container { width: 2600px; height: 1000px; background: url('../img/world-map.png') no-repeat } When we run our app, we can scroll the map in every direction. The following example shows the North America part of the map. We can scroll this map to any part that we want. Let us scroll it to show Asia. There are other attributes, which can be applied to the ion-scroll. You can check them in the following table. An Infinite scroll is used to trigger some behavior when scrolling passes the bottom of the page. The following example shows how this works. In our controller, we created a function for adding items to the list. These items will be added when a scroll passes 10% of the last element loaded. This will continue until we hit 30 loaded elements. Every time loading is finished, on-infinite will broadcast scroll.infiniteScrollComplete event. <ion-list> <ion-item ng-repeat = "item in items" item = "item">Item {{ item.id }}</ion-item> </ion-list> <ion-infinite-scroll ng-if = "!noMoreItemsAvailable" on-infinite = "loadMore()" distance = "10%"></ion-infinite-scroll> .controller('MyCtrl', function($scope) { $scope.items = []; $scope.noMoreItemsAvailable = false; $scope.loadMore = function() { $scope.items.push({ id: $scope.items.length}); if ($scope.items.length == 30) { $scope.noMoreItemsAvailable = true; } $scope.$broadcast('scroll.infiniteScrollComplete'); }; }) Other attributes can also be used with ion-infinite-scroll. Some of them are listed in the table below. Ionic offers delegate for full control of the scroll elements. It can be used by injecting a $ionicScrollDelegate service to the controller, and then use the methods it provides. The following example shows a scrollable list of 20 objects. <div class = "list"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> <div class = "item">Item 4</div> <div class = "item">Item 5</div> <div class = "item">Item 6</div> <div class = "item">Item 7</div> <div class = "item">Item 8</div> <div class = "item">Item 9</div> <div class = "item">Item 10</div> <div class = "item">Item 11</div> <div class = "item">Item 12</div> <div class = "item">Item 13</div> <div class = "item">Item 14</div> <div class = "item">Item 15</div> <div class = "item">Item 16</div> <div class = "item">Item 17</div> <div class = "item">Item 18</div> <div class = "item">Item 19</div> <div class = "item">Item 20</div> </div> <button class = "button" ng-click = "scrollTop()">Scroll to Top!</button> .controller('DashCtrl', function($scope, $ionicScrollDelegate) { $scope.scrollTop = function() { $ionicScrollDelegate.scrollTop(); }; }) The above code will produce the following screen − When we tap the button, the scroll will be moved to the top. Now, we will go through all of the $ionicScrollDelegate methods. Side menu is one of the most used Ionic components. The Side menu can be opened by swiping to the left or right or by triggering the button created for that purpose. The first element that we need is ion-side-menus. This element is used for connecting the side menu with all the screens that will use it. The ion-side-menu-content element is where the content will be placed and the ion-side-menu element is the place where we can put a side directive. We will add the side menu to the index.html and place the ion-nav-view inside the side menu content. This way the side menu can be used throughout entire app. <ion-side-menus> <ion-side-menu>side = "left"> <h1>SIde Menu</h1> </ion-side-menu> <ion-side-menu-content> <ion-nav-view> </ion-nav-view> </ion-side-menu-content> </ion-side-menus> Now, we will create button with menu-toggle = "left" directive. This button will usually be placed in the apps header bar, but we will add it in our template file for better understanding. When the button is tapped or when we swipe to the right, the side menu will open. You could also set the menu-close directive, if you would like to have one button only for closing side menu, but we will use the toggle button for this. <button menu-toggle = "left" class = "button button-icon icon ion-navicon"></button> The above code will produce the following screen − You can add some additional attributes to the ion-side-menus element. The enable-menu-with-back-views can be set to false to disable side menu, when the back button is showed. This will also hide the menu-toggle button from the header. The other attribute is delegate-handle, which will be used for the connection with $ionicSideMenuDelegate. The ion-side-menu-content element can use its own attribute. When the drag-content attribute is set to false, it will disable the ability to open the side menu by swiping the content screen. The edge-drag-threshold attribute has a default value of 25. This means that swiping is allowed only 25 pixels from the left and right edge of the screen. We can change this number value or we can set it to false to enable swiping on the entire screen or true to disable it. The ion-side-menu can use the side attribute that we showed in the example above. It will determine whether the menu should appear from the left or the right side. The ‘is-enabled’ attribute with a false value will disable the side menu, and the width attribute value is a number that represents how wide the side menu should be. The default value is 275. The $ionicSideMenuDelegate is a service used for controlling all the side menus in the app. We will show you how to use it, and then we will go through all the options available. Like all the Ionic services, we need to add it as a dependency to our controller and then use it inside the controller’s scope. Now, when we click the button, all of the side menus will open. .controller('MyCtrl', function($scope, $ionicSideMenuDelegate) { $scope.toggleLeftSideMenu = function() { $ionicSideMenuDelegate.toggleLeft(); }; }) <button class = "button button-icon icon ion-navicon" ng-click = "toggleLeft()"></button> The following table shows the $ionicScrollDelegate methods. A Slide box contains pages that can be changed by swiping the content screen. The usage of the slide box is simple. You just need to add ion-slide-box as a container and ion-slide with box class inside that container. We will add height and border to our boxes for better visibility. <ion-slide-box> <ion-slide> <div class = "box box1"> <h1>Box 1</h1> </div> </ion-slide> <ion-slide> <div class = "box box2"> <h1>Box 2</h1> </div> </ion-slide> <ion-slide> <div class = "box box3"> <h1>Box 3</h1> </div> </ion-slide> </ion-slide-box> .box1, box2, box3 { height: 300px; border: 2px solid blue; } The Output will look as shown in the following screenshot − We can change the box by dragging the content to the right. We can also drag to the left to show the previous box. A few attributes that can be used for controlling slide box behavior are mentioned in the following table. The $ionicSlideBoxDelegate is a service used for controlling all slide boxes. We need to inject it to the controller. .controller('MyCtrl', function($scope, $ionicSlideBoxDelegate) { $scope.nextSlide = function() { $ionicSlideBoxDelegate.next(); } }) <button class = "button button-icon icon ion-navicon" ng-click = "nextSlide()"></button> The following table shows $ionicSlideBoxDelegate methods. Tabs are a useful pattern for any navigation type or selecting different pages inside your app. The same tabs will appear at the top of the screen for Android devices and at the bottom for IOS devices. Tabs can be added to the app by using ion-tabs as a container element and ion-tab as a content element. We will add it to the index.html, but you can add it to any HTML file inside your app. Just be sure not to add it inside the ion-content to avoid CSS issues that comes with it. <ion-tabs class = "tabs-icon-only"> <ion-tab title = "Home" icon-on = "ion-ios-filing" icon-off = "ion-ios-filing-outline"></ion-tab> <ion-tab title = "About" icon-on = "ion-ios-home" icon-off = "ion-ios-home-outline"></ion-tab> <ion-tab title = "Settings" icon-on = "ion-ios-star" icon-off = "ion-ios-star-outline"></ion-tab> </ion-tabs> The output will look as shown in the following screenshot. There is API available for ion-tab elements. You can add it as attributes as showed in example above where we used title, icon-on and icon-off. The last two are used to differentiate selected tab from the rest of it. If you look at the image above, you can see that first tab is selected. You can check the rest of the attributes in the following table. Tabs also have its own delegate service for easier control of all the tabs inside the app. It can be injected in the controller and has several methods, which are shown in the following table. Cordova offers ngCordova, which is set of wrappers specifically designed to work with AngularJS. When you the start Ionic app, you will notice that it is using bower. It can be used for managing ngCordova plugins. If you have bower installed skip this step, if you do not have it, then you can install it in the command prompt window. C:\Users\Username\Desktop\MyApp> npm install -g bower Now we need to install ngCordova. Open your app in the command prompt window. The following example is used for the app that is located on the desktop and is named MyApp. C:\Users\Username\Desktop\MyApp> bower install ngCordova Next, we need to include ngCordova to our app. Open index.html file and add the following scripts. It is important to add these scripts before cordova.js and after ionic scripts. <script src = "lib/ngCordova/dist/ng-cordova.js"></script> Now, we need to inject ngCordova as angular dependency. Open your app.js file and add the ngCordova to angular module. If you have used one of the Ionic template apps, you will notice that there is injected ionic, controllers and services. In that case, you will just add ngCordova at the end of the array. angular.module('myApp', ['ngCordova']) You can always check the plugins that are already installed by typing the following command. C:\Users\Username\Desktop\MyApp> cordova plugins ls Now, we can use the Cordova plugins. You can check all the other plugins here. The Cordova AdMob plugin is used for integrating ads natively. We will use the admobpro plugin in this chapter, since the admob is deprecated. To be able to use ads in your app, you need to sign up to admob and create a banner. When you do this, you will get an Ad Publisher ID. Since these steps are not a part of the Ionic framework, we will not explain it here. You can follow the steps by Google support team here. You will also need to have android or iOS platform installed, since the cordova plugins work only on native platforms. We have already discussed how to do this in our environment setup chapter. The AdMob plugin can be installed in the command prompt window. C:\Users\Username\Desktop\MyApp> cordova plugin add cordova-plugin-admobpro Now that we have installed the plugin, we need to check if the device is ready before we are able to use it. This is why we need to add the following code in the $ionicPlatform.ready function inside the app.js. if( ionic.Platform.isAndroid() ) { admobid = { // for Android banner: 'ca-app-pub-xxx/xxx' // Change this to your Ad Unit Id for banner... }; if(AdMob) AdMob.createBanner( { adId:admobid.banner, position:AdMob.AD_POSITION.BOTTOM_CENTER, autoShow:true } ); } The output will look as shown in the following screenshot. The same code can be applied for iOS or a Windows Phone. You will only use a different id for these platforms. Instead of a banner, you can use interstitial ads that will cover entire screen. The following table shows methods that can be used with admob. The following table shows the events that can be used with admob. You can handle these events by following the example below. document.addEventListener('onAdLoaded', function(e){ // Handle the event... }); The Cordova camera plugin uses the native camera for taking pictures or getting images from the image gallery. Open your project root folder in command prompt, then download and install the Cordova camera plugin with the following command. C:\Users\Username\Desktop\MyApp> cordova plugin add org.apache.cordova.camera Now, we will create a service for using a camera plugin. We will use the AngularJS factory and promise object $q that needs to be injected to the factory. .factory('Camera', function($q) { return { getPicture: function(options) { var q = $q.defer(); navigator.camera.getPicture(function(result) { q.resolve(result); }, function(err) { q.reject(err); }, options); return q.promise; } } }); To use this service in the app, we need to inject it to a controller as a dependency. Cordova camera API provides the getPicture method, which is used for taking photos using a native camera. The native camera settings can be additionally customized by passing the options parameter to the takePicture function. Copy the above-mentioned code sample to your controller to trigger this behavior. It will open the camera application and return a success callback function with the image data or error callback function with an error message. We will also need two buttons that will call the functions we are about to create and we need to show the image on the screen. <button class = "button" ng-click = "takePicture()">Take Picture</button> <button class = "button" ng-click = "getPicture()">Open Gallery</button> <img ng-src = "{{user.picture}}"> .controller('MyCtrl', function($scope, Camera) { $scope.takePicture = function (options) { var options = { quality : 75, targetWidth: 200, targetHeight: 200, sourceType: 1 }; Camera.getPicture(options).then(function(imageData) { $scope.picture = imageData;; }, function(err) { console.log(err); }); }; }) The output will look as shown in the following screenshot. If you want to use images from your gallery, the only thing you need to change is the sourceType method from your options parameter. This change will open a dialog popup instead of camera and allow you to choose the image you want from the device. You can see the following code, where the sourceType option is changed to 0. Now, when you tap the second button, it will open the file menu from the device. .controller('MyCtrl', function($scope, Camera) { $scope.getPicture = function (options) { var options = { quality : 75, targetWidth: 200, targetHeight: 200, sourceType: 0 }; Camera.getPicture(options).then(function(imageData) { $scope.picture = imageData;; }, function(err) { console.log(err); }); }; }) The output will look as shown in the following screenshot. When you save the image you took, it will appear on the screen. You can style it the way you want. Several other options can be used as well, some of which are given in the following table. This plugin is used for connecting to Facebook API. Before you start integrating Facebook, you need to create a Facebook app here. You will create a web app and then skip the quick start screen. Then, you need to add the website platform on the settings page. You can use the following code snippet for the site URL while in development. http://localhost:8100/ After that, you need to add Valid OAuth redirect URIs on the settings/advanced page. Just copy the following two URLs. https://www.facebook.com/connect/login_success.html http://localhost:8100/oauthcallback.html We did all the steps above to tackle some issues that often appear when using this plugin. This plugin is hard to set up because there are a lot of steps involved and documentation doesn't cover all of them. There are also some known compatibility issues with other Cordova plugins, so we will use Teleric verified plugin version in our app. We will start by installing browser platform to our app from the command prompt. C:\Users\Username\Desktop\MyApp>ionic platform add browser Next, what we need to do is to add the root element on top of the body tag in index.html. <div id = "fb-root"></div> Now we will add Cordova Facebook plugin to our app. You need to change APP_ID and APP_NAME to match the Facebook app you created before. C:\Users\Username\Desktop\MyApp>cordova -d plugin add https://github.com/Telerik-Verified-Plugins/Facebook/ --variable APP_ID = "123456789" --variable APP_NAME = "FbAppName" Now open index.html and add the following code after your body tag. Again you need to make sure that the appId and version are matching the Facebook app you created. This will ensure that Facebook SDK is loaded asynchronously without blocking the rest of the app. <script> window.fbAsyncInit = function() { FB.init({ appId : '123456789', xfbml : true, version : 'v2.4' }); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> Since we installed everything, we need to create service that will be our connection to the Facebook. These things can be done with less code inside the controller, but we try to follow the best practices, so we will use Angular service. The following code shows the entire service. We will explain it later. .service('Auth', function($q, $ionicLoading) { this.getLoginStatus = function() { var defer = $q.defer(); FB.getLoginStatus(function(response) { if (response.status === "connected") { console.log(JSON.stringify(response)); } else { console.log("Not logged in"); } }); return defer.promise; } this.loginFacebook = function() { var defer = $q.defer(); FB.login(function(response) { if (response.status === "connected") { console.log(JSON.stringify(response)); } else { console.log("Not logged in!"); } }); return defer.promise; } this.logoutFacebook = function() { var defer = $q.defer(); FB.logout(function(response) { console.log('You are logged out!'); }); return defer.promise; } this.getFacebookApi = function() { var defer = $q.defer(); FB.api("me/?fields = id,email", [], function(response) { if (response.error) { console.log(JSON.stringify(response.error)); } else { console.log(JSON.stringify(response)); } }); return defer.promise; } }); In the above service, we are creating four functions. First three are self-explanatory. The fourth function is used for connecting to Facebook graph API. It will return the id and email from the Facebook user. We are creating promise objects to handle asynchronic JavaScript functions. Now we need to write our controller that will call those functions. We will call each function separately for better understanding, but you will probably need to mix some of them together to get the desired effect. .controller('MyCtrl', function($scope, Auth, $ionicLoading) { $scope.checkLoginStatus = function() { getLoginUserStatus(); } $scope.loginFacebook = function(userData) { loginFacebookUser(); }; $scope.facebookAPI = function() { getFacebookUserApi(); } $scope.logoutFacebook = function() { logoutFacebookUser(); }; function loginFacebookUser() { return Auth.loginFacebook(); } function logoutFacebookUser() { return Auth.logoutFacebook(); } function getFacebookUserApi() { return Auth.getFacebookApi(); } function getLoginUserStatus() { return Auth.getLoginStatus(); } }) You are probably wondering why didn't we returned Auth service directly from the function expressions (first four functions). The reason for this is that you will probably want to add some more behavior after the Auth function is returned. You might send some data to your database, change the route after login, etc. This can be easily done by using JavaScript then() method to handle all the asynchronous operations instead of callbacks. Now we need to allow users to interact with the app. Our HTML will contain four buttons for calling the four functions we created. <button class = "button" ng-click = "loginFacebook()">LOG IN</button> <button class = "button" ng-click = "logoutFacebook()">LOG OUT</button> <button class = "button" ng-click = "checkLoginStatus()">CHECK</button> <button class = "button" ng-click = "facebookAPI()">API</button> When the user taps the LOG IN button, the Facebook screen will appear. The user will be redirected to the app after the login is successful. The Cordova InAppBrowser plugin is used to open external links from your app inside a web browser view. It is very easy to start working with this plugin. All you need to do is to open the command prompt window and install the Cordova plugin. C:\Users\Username\Desktop\MyApp>cordova plugin add org.apache.cordova.inappbrowser This step allows us to start using the inAppBrowser. We can now create a button that will lead us to some external link, and add a simple function for triggering the plugin. <button class = "button" ng-click = "openBrowser()">OPEN BROWSER</button> .controller('MyCtrl', function($scope, $cordovaInAppBrowser) { var options = { location: 'yes', clearcache: 'yes', toolbar: 'no' }; $scope.openBrowser = function() { $cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options) .then(function(event) { // success }) .catch(function(event) { // error }); } }) When the user taps the button the InAppBrowser will open the URL we provided. Several other methods can be used with this plugin, some of which are in the following table. This plugin also offers events that can be combined with $rootScope. This plugin is used for adding native audio sounds to the Ionic app. To be able to use this plugin, we first need to install it. Open the command prompt window and add the Cordova plugin. C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-nativeaudio Before we start using this plugin, we will need audio file. For simplicity, we will save our click.mp3 file inside the js folder, but you can place it wherever you want. The next step is to preload the audio file. There are two options available, which are − preloadSimple − It is used for simple sounds that will be played once. preloadSimple − It is used for simple sounds that will be played once. preloadComplex − It is for sounds that will be played as looping sounds or background audio. preloadComplex − It is for sounds that will be played as looping sounds or background audio. Add the following code to your controller to preload an audio file. We need to be sure that the Ionic platform is loaded before we can preload the audio file. $ionicPlatform.ready(function() { $cordovaNativeAudio .preloadSimple('click', 'js/click.mp3') .then(function (msg) { console.log(msg); }, function (error) { console.log(error); }); $cordovaNativeAudio.preloadComplex('click', 'js/click.mp3', 1, 1) .then(function (msg) { console.log(msg); }, function (error) { console.error(error); }); }); In the same controller, we will add code for playing audio. Our $timeout function will stop and unload looping audio after five seconds. $scope.playAudio = function () { $cordovaNativeAudio.play('click'); }; $scope.loopAudio = function () { $cordovaNativeAudio.loop('click'); $timeout(function () { $cordovaNativeAudio.stop('click'); $cordovaNativeAudio.unload('click'); }, 5000); } The last thing we need is to create buttons for playing and looping audio. <button class = "button" ng-click = "playAudio()">PLAY</button> <button class = "button" ng-click = "loopAudio()">LOOP</button> When we tap on play button, we will hear the sound once and when we tap on the loop button, the sound will loop for five seconds and then stop. This plugin works only on an emulator or a mobile device. This plugin is used for adding a geolocation plugin to the Ionic app. There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window. C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-geolocation The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPosition method that will return the current position of the device when the position is changed. .controller('MyCtrl', function($scope, $cordovaGeolocation) { var posOptions = {timeout: 10000, enableHighAccuracy: false}; $cordovaGeolocation .getCurrentPosition(posOptions) .then(function (position) { var lat = position.coords.latitude var long = position.coords.longitude console.log(lat + ' ' + long) }, function(err) { console.log(err) }); var watchOptions = {timeout : 3000, enableHighAccuracy: false}; var watch = $cordovaGeolocation.watchPosition(watchOptions); watch.then( null, function(err) { console.log(err) }, function(position) { var lat = position.coords.latitude var long = position.coords.longitude console.log(lat + '' + long) } ); watch.clearWatch(); }) You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option. When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change. This plugin allows us to record and playback audio files on a device. As with all the other Cordova plugins, the first thing we need to do is to install it from the command prompt window. C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-media Now, we are ready to use the plugin. In the following code sample, src is the source mp3 file that we will use for this tutorial. It is placed in js folder, but we need to add /android_asset/www/ before it, so it can be used on android devices. The complete functionality is wrapped inside the $ionicPlatform.ready() function to assure that everything is loaded before the plugin is used. After that, we are creating the media object by using the newMedia(src) method. The media object is used for adding play, pause, stop and release functionalities. .controller('MyCtrl', function($scope, $ionicPlatform, $cordovaMedia) { $ionicPlatform.ready(function() { var src = "/android_asset/www/js/song.mp3"; var media = $cordovaMedia.newMedia(src); $scope.playMedia = function() { media.play(); }; $scope.pauseMedia = function() { media.pause(); }; $scope.stopMedia = function() { media.stop(); }; $scope.$on('destroy', function() { media.release(); }); }); } We will also create three buttons for calling play, pause and stop functions. <button class = "button" ng-click = "playMedia()">PLAY</button> <button class = "button" ng-click = "pauseMedia()">PAUSE</button> <button class = "button" ng-click = "stopMedia()">STOP</button> We need to run it on an emulator or a mobile device for this plugin to work. When the user’s tap on the play button, the song.mp3 will start playing. You can see in the above example that we use src as an option parameter. There are other optional parameters that can be used for the newMedia method. The following table will show all the optional parameters available. The next table will show all the methods available. The following table will show all the methods available. Every mobile app needs an icon and splash screen. Ionic provides excellent solution for adding it and requires minimum work for the developers. Cropping and resizing is automated on the Ionic server. In the earlier chapters, we have discussed how to add different platforms for the Ionic app. By adding a platform, Ionic will install Cordova splash screen plugin for that platform so we do not need to install anything afterwards. All we need to do is to find two images. The images should be png, psd or ai files. The minimum dimension should be 192x192 for icon image and 2208×2208 for the splash screen image. This dimensions will cover all the devices. In our example, we will use the same image for both. The images need to be saved to resources folder instead of the default ones. After we are done with it, all we need is to run the following in the command prompt window. C:\Users\Username\Desktop\MyApp>ionic resources Now, if you check resources/android or resources/ios folders, you will see that the images we added before are resized and cropped to accommodate different screen sizes. When we run our app on the device, we will see a splash screen before the app is started and we will see that a default Ionic icon is changed. NOTE − If you want to use different images for Android and iOS, you can add it to resources/android and resources/ios instead of the resources folder. 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2637, "s": 2463, "text": "Ionic is a front-end HTML framework built on top of AngularJS and Cordova. As per their official document, the definition of this Ionic Open Source Framework is as follows −" }, { "code": null, "e": 3015, "s": 2637, "text": "Ionic is an HTML5 Mobile App Development Framework targeted at building hybrid mobile apps. Think of Ionic as the front-end UI framework that handles all the look and feel and UI interactions your app needs to be compelling. Kind of like \"Bootstrap for Native\", but with the support for a broad range of common native mobile components, slick animations and a beautiful design." }, { "code": null, "e": 3068, "s": 3015, "text": "Following are the most important features of Ionic −" }, { "code": null, "e": 3195, "s": 3068, "text": "AngularJS − Ionic is using AngularJS MVC architecture for building rich single page applications optimized for mobile devices." }, { "code": null, "e": 3322, "s": 3195, "text": "AngularJS − Ionic is using AngularJS MVC architecture for building rich single page applications optimized for mobile devices." }, { "code": null, "e": 3536, "s": 3322, "text": "CSS components − With the native look and feel, these components offer almost all elements that a mobile application needs. The components’ default styling can be easily overridden to accommodate your own designs." }, { "code": null, "e": 3750, "s": 3536, "text": "CSS components − With the native look and feel, these components offer almost all elements that a mobile application needs. The components’ default styling can be easily overridden to accommodate your own designs." }, { "code": null, "e": 3925, "s": 3750, "text": "JavaScript components − These components are extending CSS components with JavaScript functionalities to cover all mobile elements that cannot be done only with HTML and CSS." }, { "code": null, "e": 4100, "s": 3925, "text": "JavaScript components − These components are extending CSS components with JavaScript functionalities to cover all mobile elements that cannot be done only with HTML and CSS." }, { "code": null, "e": 4214, "s": 4100, "text": "Cordova Plugins − Apache Cordova plugins offer API needed for using native device functions with JavaScript code." }, { "code": null, "e": 4328, "s": 4214, "text": "Cordova Plugins − Apache Cordova plugins offer API needed for using native device functions with JavaScript code." }, { "code": null, "e": 4451, "s": 4328, "text": "Ionic CLI − This is NodeJS utility powered with commands for starting, building, running and emulating Ionic applications." }, { "code": null, "e": 4574, "s": 4451, "text": "Ionic CLI − This is NodeJS utility powered with commands for starting, building, running and emulating Ionic applications." }, { "code": null, "e": 4679, "s": 4574, "text": "Ionic View − Very useful platform for uploading, sharing and testing your application on native devices." }, { "code": null, "e": 4784, "s": 4679, "text": "Ionic View − Very useful platform for uploading, sharing and testing your application on native devices." }, { "code": null, "e": 4831, "s": 4784, "text": "Licence − Ionic is released under MIT license." }, { "code": null, "e": 4878, "s": 4831, "text": "Licence − Ionic is released under MIT license." }, { "code": null, "e": 4953, "s": 4878, "text": "Following are some of the most commonly known Ionic Framework Advantages −" }, { "code": null, "e": 5135, "s": 4953, "text": "Ionic is used for Hybrid App Development. This means that you can package your applications for IOS, Android, Windows Phone and Firefox OS, which can save you a lot of working time." }, { "code": null, "e": 5317, "s": 5135, "text": "Ionic is used for Hybrid App Development. This means that you can package your applications for IOS, Android, Windows Phone and Firefox OS, which can save you a lot of working time." }, { "code": null, "e": 5421, "s": 5317, "text": "Starting your app is very easy since Ionic provides useful pre-generated app setup with simple layouts." }, { "code": null, "e": 5525, "s": 5421, "text": "Starting your app is very easy since Ionic provides useful pre-generated app setup with simple layouts." }, { "code": null, "e": 5624, "s": 5525, "text": "The apps are built in a very clean and modular way, so it is very maintainable and easy to update." }, { "code": null, "e": 5723, "s": 5624, "text": "The apps are built in a very clean and modular way, so it is very maintainable and easy to update." }, { "code": null, "e": 5963, "s": 5723, "text": "Ionic Developers Team have a very good relationship with the Google Developers Team and they are working together to improve the framework. The updates are coming out regularly and Ionic support group is always willing to help when needed." }, { "code": null, "e": 6203, "s": 5963, "text": "Ionic Developers Team have a very good relationship with the Google Developers Team and they are working together to improve the framework. The updates are coming out regularly and Ionic support group is always willing to help when needed." }, { "code": null, "e": 6274, "s": 6203, "text": "Following are some of the most important Ionic Framework Limitations −" }, { "code": null, "e": 6491, "s": 6274, "text": "Testing can be tricky since the browser does not always give you the right information about the phone environment. There are so many different devices as well as platforms and you usually need to cover most of them." }, { "code": null, "e": 6708, "s": 6491, "text": "Testing can be tricky since the browser does not always give you the right information about the phone environment. There are so many different devices as well as platforms and you usually need to cover most of them." }, { "code": null, "e": 6903, "s": 6708, "text": "It can be hard to combine different native functionalities. There will be many instances where you would run into plugin compatibility issues, which leads to build errors that are hard to debug." }, { "code": null, "e": 7098, "s": 6903, "text": "It can be hard to combine different native functionalities. There will be many instances where you would run into plugin compatibility issues, which leads to build errors that are hard to debug." }, { "code": null, "e": 7249, "s": 7098, "text": "Hybrid apps tend to be slower than the native ones. However, since the mobile technologies are improving fast this will not be an issue in the future." }, { "code": null, "e": 7400, "s": 7249, "text": "Hybrid apps tend to be slower than the native ones. However, since the mobile technologies are improving fast this will not be an issue in the future." }, { "code": null, "e": 7498, "s": 7400, "text": "In the next chapter, we will understand the environment setup of the Ionic Open Source Framework." }, { "code": null, "e": 7640, "s": 7498, "text": "This chapter will show you how to start with Ionic Framework. The following table contains the list of components needed to start with Ionic." }, { "code": null, "e": 7647, "s": 7640, "text": "NodeJS" }, { "code": null, "e": 7851, "s": 7647, "text": "This is the base platform needed to create Mobile Apps using Ionic. You can find detail on the NodeJS installation in our NodeJS Environment Setup. Make sure you also install npm while installing NodeJS." }, { "code": null, "e": 7863, "s": 7851, "text": "Android SDK" }, { "code": null, "e": 8099, "s": 7863, "text": "If you are going to work on a Windows platform and are developing your apps for the Android platform, then you should have Android SDK setup on your machine. The following link has detailed information on the Android Environment Setup." }, { "code": null, "e": 8105, "s": 8099, "text": "XCode" }, { "code": null, "e": 8325, "s": 8105, "text": "If you are going to work on the Mac platform and are developing your apps for the iOS platform, then you should have XCode setup on your machine. The following link has detailed information on the iOS Environment Setup." }, { "code": null, "e": 8343, "s": 8325, "text": "cordova and Ionic" }, { "code": null, "e": 8546, "s": 8343, "text": "These are the main SDKs which is needed to start working with Ionic. This chapter explains how to setup Ionic in simple step assuming you already have the required setup as explained in the table above." }, { "code": null, "e": 8711, "s": 8546, "text": "We will use the Windows command prompt for this tutorial. The same steps can be applied to the OSX terminal. Open your command window to install Cordova and Ionic −" }, { "code": null, "e": 8760, "s": 8711, "text": "C:\\Users\\Username> npm install -g cordova ionic\n" }, { "code": null, "e": 8854, "s": 8760, "text": "While creating apps in Ionic, you can choose from the following three options to start with −" }, { "code": null, "e": 8863, "s": 8854, "text": "Tabs App" }, { "code": null, "e": 8873, "s": 8863, "text": "Blank App" }, { "code": null, "e": 8887, "s": 8873, "text": "Side menu app" }, { "code": null, "e": 9004, "s": 8887, "text": "In your command window, open the folder where you want to create the app and try one of the options mentioned below." }, { "code": null, "e": 9255, "s": 9004, "text": "If you want to use the Ionic tabs template, the app will be built with the tab menu, header and a couple of useful screens and functionalities. This is the default Ionic template. Open your command window and choose where you want to create your app." }, { "code": null, "e": 9286, "s": 9255, "text": "C:\\Users\\Username> cd Desktop\n" }, { "code": null, "e": 9374, "s": 9286, "text": "This command will change the working directory. The app will be created on the Desktop." }, { "code": null, "e": 9425, "s": 9374, "text": "C:\\Users\\Username\\Desktop> ionic start myApp tabs\n" }, { "code": null, "e": 9513, "s": 9425, "text": "Ionic Start command will create a folder named myApp and setup Ionic files and folders." }, { "code": null, "e": 9550, "s": 9513, "text": "C:\\Users\\Username\\Desktop> cd myApp\n" }, { "code": null, "e": 9637, "s": 9550, "text": "Now, we want to access the myApp folder that we just created. This is our root folder." }, { "code": null, "e": 9825, "s": 9637, "text": "Let us now add the Cordova project for the Android Platform and install the basic Cordova plugins as well. The following code allows us to run the app on the Android emulator or a device." }, { "code": null, "e": 9886, "s": 9825, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic platform add android\n" }, { "code": null, "e": 10053, "s": 9886, "text": "The next step is to build the app. If you have building errors after running the following command, you probably did not install the Android SDK and its dependencies." }, { "code": null, "e": 10107, "s": 10053, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic build android\n" }, { "code": null, "e": 10390, "s": 10107, "text": "The last step of the installation process is to run your app, which will start the mobile device, if connected, or the default emulator, if there is no device connected. Android Default Emulator is slow, so I suggest you to install Genymotion or some other popular Android Emulator." }, { "code": null, "e": 10442, "s": 10390, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic run android\n" }, { "code": null, "e": 10502, "s": 10442, "text": "This will produce below result, which is an Ionic Tabs App." }, { "code": null, "e": 10732, "s": 10502, "text": "If you want to start from the scratch, you can install the Ionic blank template. We will use the same steps that have been explained above with the addition of ionic start myApp blank instead of ionic start myApp tabs as follows." }, { "code": null, "e": 10784, "s": 10732, "text": "C:\\Users\\Username\\Desktop> ionic start myApp blank\n" }, { "code": null, "e": 10880, "s": 10784, "text": "The Ionic Start command will create a folder named myApp and setup the Ionic files and folders." }, { "code": null, "e": 10917, "s": 10880, "text": "C:\\Users\\Username\\Desktop> cd myApp\n" }, { "code": null, "e": 11031, "s": 10917, "text": "Let us add the Cordova project for the Android Platform and install the basic Cordova plugins as explained above." }, { "code": null, "e": 11091, "s": 11031, "text": "C:\\Users\\Username\\Desktop\\myApp>ionic platform add android\n" }, { "code": null, "e": 11127, "s": 11091, "text": "The next step is to build our app −" }, { "code": null, "e": 11181, "s": 11127, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic build android\n" }, { "code": null, "e": 11241, "s": 11181, "text": "Finally, we will start the App as with the following code −" }, { "code": null, "e": 11293, "s": 11241, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic run android\n" }, { "code": null, "e": 11361, "s": 11293, "text": "This will produce the following result, which is a Ionic Blank App." }, { "code": null, "e": 11554, "s": 11361, "text": "The third template that you can use is the Side Menu Template. The steps are the same as the previous two templates; we will just add sidemenu when starting our app as shown in the code below." }, { "code": null, "e": 11609, "s": 11554, "text": "C:\\Users\\Username\\Desktop> ionic start myApp sidemenu\n" }, { "code": null, "e": 11705, "s": 11609, "text": "The Ionic Start command will create a folder named myApp and setup the Ionic files and folders." }, { "code": null, "e": 11742, "s": 11705, "text": "C:\\Users\\Username\\Desktop> cd myApp\n" }, { "code": null, "e": 11863, "s": 11742, "text": "Let us add the Cordova project for the Android Platform and install the basic Cordova plugins with the code given below." }, { "code": null, "e": 11924, "s": 11863, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic platform add android\n" }, { "code": null, "e": 11983, "s": 11924, "text": "The next step is to build our app with the following code." }, { "code": null, "e": 12037, "s": 11983, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic build android\n" }, { "code": null, "e": 12095, "s": 12037, "text": "Finally, we will start the App with the code given below." }, { "code": null, "e": 12147, "s": 12095, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic run android\n" }, { "code": null, "e": 12220, "s": 12147, "text": "This will produce the following result, which is an Ionic Side Menu App." }, { "code": null, "e": 12478, "s": 12220, "text": "Since we are working with the JavaScript, you can serve your app on any web browser. This will speed up your building process, but you should always test your app on native emulators and devices. Type the following code to serve your app on the web browser." }, { "code": null, "e": 12524, "s": 12478, "text": "C:\\Users\\Username\\Desktop\\myApp> ionic serve\n" }, { "code": null, "e": 12709, "s": 12524, "text": "The above command will open your app in the web browser. Google Chrome provides the device mode functionality for mobile development testing. Press F12 to access the developer console." }, { "code": null, "e": 12949, "s": 12709, "text": "The top left corner of the console window click has the \"Toggle Device Mode\" icon. The next step will be to click \"Dock to Right\" icon in the top right corner. Once the page is refreshed, you should be ready for testing on the web browser." }, { "code": null, "e": 13138, "s": 12949, "text": "Ionic creates the following directory structure for all type of apps. This is important for any Ionic developer to understand the purpose of every directory and the files mentioned below −" }, { "code": null, "e": 13269, "s": 13138, "text": "Let us have a quick understanding of all the folders and files available in the project folder structure shown in the image above." }, { "code": null, "e": 13492, "s": 13269, "text": "Hooks − Hooks are scripts that can be triggered during the build process. They are usually used for the Cordova commands customization and for building automated processes. We will not use this folder during this tutorial." }, { "code": null, "e": 13715, "s": 13492, "text": "Hooks − Hooks are scripts that can be triggered during the build process. They are usually used for the Cordova commands customization and for building automated processes. We will not use this folder during this tutorial." }, { "code": null, "e": 13943, "s": 13715, "text": "Platforms − This is the folder where Android and IOS projects are created. You might encounter some platform specific problems during development that will require these files, but you should leave them intact most of the time." }, { "code": null, "e": 14171, "s": 13943, "text": "Platforms − This is the folder where Android and IOS projects are created. You might encounter some platform specific problems during development that will require these files, but you should leave them intact most of the time." }, { "code": null, "e": 14374, "s": 14171, "text": "Plugins − This folder contains Cordova plugins. When you initially create an Ionic app, some of the plugins will be installed. We will show you how to install Cordova plugins in our subsequent chapters." }, { "code": null, "e": 14577, "s": 14374, "text": "Plugins − This folder contains Cordova plugins. When you initially create an Ionic app, some of the plugins will be installed. We will show you how to install Cordova plugins in our subsequent chapters." }, { "code": null, "e": 14675, "s": 14577, "text": "Resources − This folder is used for adding resources like icon and splash screen to your project." }, { "code": null, "e": 14773, "s": 14675, "text": "Resources − This folder is used for adding resources like icon and splash screen to your project." }, { "code": null, "e": 14974, "s": 14773, "text": "Scss − Since Ionic core is built with Sass, this is the folder where your Sass file is located. For simplifying the process, we will not use Sass for this tutorial. Our styling will be done using CSS." }, { "code": null, "e": 15175, "s": 14974, "text": "Scss − Since Ionic core is built with Sass, this is the folder where your Sass file is located. For simplifying the process, we will not use Sass for this tutorial. Our styling will be done using CSS." }, { "code": null, "e": 15892, "s": 15175, "text": "www − www is the main working folder for Ionic developers. They spend most of their time here. Ionic gives us their default folder structure inside 'www', but the developers can always change it to accommodate their own needs. When this folder is opened, you will find the following sub-folders −\n\nThe css folder, where you will write your CSS styling.\nThe img folder for storing images.\nThe js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders.\nThe libs folder, where your libraries will be placed.\nThe templates folder for your HTML files.\nIndex.html as a starting point to your app.\n\n" }, { "code": null, "e": 16189, "s": 15892, "text": "www − www is the main working folder for Ionic developers. They spend most of their time here. Ionic gives us their default folder structure inside 'www', but the developers can always change it to accommodate their own needs. When this folder is opened, you will find the following sub-folders −" }, { "code": null, "e": 16244, "s": 16189, "text": "The css folder, where you will write your CSS styling." }, { "code": null, "e": 16299, "s": 16244, "text": "The css folder, where you will write your CSS styling." }, { "code": null, "e": 16334, "s": 16299, "text": "The img folder for storing images." }, { "code": null, "e": 16369, "s": 16334, "text": "The img folder for storing images." }, { "code": null, "e": 16556, "s": 16369, "text": "The js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders." }, { "code": null, "e": 16743, "s": 16556, "text": "The js folder that contains the apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All your JavaScript code will be inside these folders." }, { "code": null, "e": 16797, "s": 16743, "text": "The libs folder, where your libraries will be placed." }, { "code": null, "e": 16851, "s": 16797, "text": "The libs folder, where your libraries will be placed." }, { "code": null, "e": 16893, "s": 16851, "text": "The templates folder for your HTML files." }, { "code": null, "e": 16935, "s": 16893, "text": "The templates folder for your HTML files." }, { "code": null, "e": 16979, "s": 16935, "text": "Index.html as a starting point to your app." }, { "code": null, "e": 17023, "s": 16979, "text": "Index.html as a starting point to your app." }, { "code": null, "e": 17745, "s": 17023, "text": "Other Files − Since this is a beginner’s tutorial, we will just mention some of the other important files and their purposes as well.\n\n.bowerrc is the bower configuration file.\n.editorconfig is the editor configuration file.\n.gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository.\nbower.json will contain the bower components and dependencies, if you choose to use the bower package manager.\ngulpfile.js is used for creating automated tasks using the gulp task manager.\nconfig.xml is the Cordova configuration file.\npackage.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager.\n\n" }, { "code": null, "e": 17879, "s": 17745, "text": "Other Files − Since this is a beginner’s tutorial, we will just mention some of the other important files and their purposes as well." }, { "code": null, "e": 17921, "s": 17879, "text": ".bowerrc is the bower configuration file." }, { "code": null, "e": 17963, "s": 17921, "text": ".bowerrc is the bower configuration file." }, { "code": null, "e": 18011, "s": 17963, "text": ".editorconfig is the editor configuration file." }, { "code": null, "e": 18059, "s": 18011, "text": ".editorconfig is the editor configuration file." }, { "code": null, "e": 18184, "s": 18059, "text": ".gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository." }, { "code": null, "e": 18309, "s": 18184, "text": ".gitignore is used to instruct which part of the app should be ignored when you want to push your app to the Git repository." }, { "code": null, "e": 18420, "s": 18309, "text": "bower.json will contain the bower components and dependencies, if you choose to use the bower package manager." }, { "code": null, "e": 18531, "s": 18420, "text": "bower.json will contain the bower components and dependencies, if you choose to use the bower package manager." }, { "code": null, "e": 18609, "s": 18531, "text": "gulpfile.js is used for creating automated tasks using the gulp task manager." }, { "code": null, "e": 18687, "s": 18609, "text": "gulpfile.js is used for creating automated tasks using the gulp task manager." }, { "code": null, "e": 18733, "s": 18687, "text": "config.xml is the Cordova configuration file." }, { "code": null, "e": 18779, "s": 18733, "text": "config.xml is the Cordova configuration file." }, { "code": null, "e": 18914, "s": 18779, "text": "package.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager." }, { "code": null, "e": 19049, "s": 18914, "text": "package.json contains the information about the apps, their dependencies and plugins that are installed using the NPM package manager." }, { "code": null, "e": 19149, "s": 19049, "text": "In the next chapter, we will discuss the different colors available in Ionic open source framework." }, { "code": null, "e": 19312, "s": 19149, "text": "Before we start with actual elements available in the Ionic framework, let us have a little understanding on how Ionic makes use of colors for different elements." }, { "code": null, "e": 19448, "s": 19312, "text": "Ionic framework gives us a set of nine predefined color classes. You can use these colors or you can override it with your own styling." }, { "code": null, "e": 19659, "s": 19448, "text": "The following table shows the default set of nine colors provided by Ionic. We will use these colors for styling different Ionic elements in this tutorial. For now, you can check all the colors as shown below −" }, { "code": null, "e": 19894, "s": 19659, "text": "Ionic makes use of different classes for each element. For example, a header element will have bar class and a button will have a button class. To simplify the usage, we use different colors by prefixing element class in a color name." }, { "code": null, "e": 19974, "s": 19894, "text": "For example, to create a blue color header, we will use a bar-calm as follows −" }, { "code": null, "e": 20029, "s": 19974, "text": "<div class = \"bar bar-header bar-calm\">\n ...\n</div>\n" }, { "code": null, "e": 20115, "s": 20029, "text": "Similarly, to create a grey color button, we will use button-stable class as follows." }, { "code": null, "e": 20167, "s": 20115, "text": "<div class = \"button button-stable\">\n ...\n</div>\n" }, { "code": null, "e": 20318, "s": 20167, "text": "You can also use Ionic color class like any other CSS class. We will now style two paragraphs with a balanced (green) and an energized (yellow) color." }, { "code": null, "e": 20402, "s": 20318, "text": "<p class = \"balanced\">Paragraph 1...</p>\n<p class = \"energized\">Paragraph 2...</p>\n" }, { "code": null, "e": 20453, "s": 20402, "text": "The above code will produce the following screen −" }, { "code": null, "e": 20566, "s": 20453, "text": "We will discuss in detail in the subsequent chapters, when we create different elements using different classes." }, { "code": null, "e": 20823, "s": 20566, "text": "When you want to change some of the Ionic default colors using CSS, you can do it by editing the lib/css/ionic.css file. In some cases, this approach is not very productive because every element (header, button, footer...) uses its own classes for styling." }, { "code": null, "e": 21147, "s": 20823, "text": "Therefore, if you want to change the color of the \"light\" class to orange, you would need to search through all the elements that use this class and change it. This is useful when you want to change the color of a single element, but not very practical for changing color of all elements because it would use too much time." }, { "code": null, "e": 21366, "s": 21147, "text": "SASS (which is the short form of – Syntactically Awesome Style Sheet) provides an easier way to change the color for all the elements at once. If you want to use SASS, open your project in the command window and type −" }, { "code": null, "e": 21423, "s": 21366, "text": "C:\\Users\\Username\\Desktop\\tutorialApp> ionic setup sass\n" }, { "code": null, "e": 21634, "s": 21423, "text": "This will set up SASS for your project. Now you can the change default colors by opening the scss/ionic.app.scss file and then typing in the following code before this line – @import \"www/lib/ionic/scss/ionic\";" }, { "code": null, "e": 21784, "s": 21634, "text": "We will change the balanced color to dark blue and the energized color to orange. The two paragraphs that we used above are now dark blue and orange." }, { "code": null, "e": 21844, "s": 21784, "text": "$balanced: #000066 !default;\n$energized: #FFA500 !default;\n" }, { "code": null, "e": 21884, "s": 21844, "text": "Now, if you use the following example −" }, { "code": null, "e": 21968, "s": 21884, "text": "<p class = \"balanced\">Paragraph 1...</p>\n<p class = \"energized\">Paragraph 2...</p>\n" }, { "code": null, "e": 22019, "s": 21968, "text": "The above code will produce the following screen −" }, { "code": null, "e": 22237, "s": 22019, "text": "All the Ionic elements that are using these classes will change to dark blue and orange. Take into consideration that you do not need to use Ionic default color classes. You can always style elements the way you want." }, { "code": null, "e": 22468, "s": 22237, "text": "The www/css/style.css file will be removed from the header of the index.html after you install SASS. You will need to link it manually if you still want to use it. Open index.html and then add the following code inside the header." }, { "code": null, "e": 22518, "s": 22468, "text": "<link href = \"css/style.css\" rel = \"stylesheet\">\n" }, { "code": null, "e": 22871, "s": 22518, "text": "Almost every mobile app contains some fundamental elements. Usually those elements include a header and a footer that will cover the top and the bottom part of the screen. All the other elements will be placed between these two. Ionic provides ion-content element that serves as a container that will wrap all the other elements that we want to create." }, { "code": null, "e": 23022, "s": 22871, "text": "This container has some unique characteristics, but since this is a JavaScript based component which we will cover in the later part of this tutorial." }, { "code": null, "e": 23431, "s": 23022, "text": "<div class = \"bar bar-header\"> \n <h1 class = \"title\">Header</h1> \n</div>\n \n<div class = \"list\"> \n <label class = \"item item-input\"> \n <input type = \"text\" placeholder = \"Placeholder 1\" /> \n </label>\n \n <label class = \"item item-input\"> \n <input type = \"text\" placeholder = \"Placeholder 2\" /> \n </label> \n</div>\n\n<div class = \"bar bar-footer\"> \n <h1 class = \"title\">Footer</h1> \n</div>" }, { "code": null, "e": 23659, "s": 23431, "text": "The Ionic header bar is located on top of the screen. It can contain title, icons, buttons or some other elements on top of it. There are predefined classes of headers that you can use. You can check all of it in this tutorial." }, { "code": null, "e": 23834, "s": 23659, "text": "The main class for all the bars you might use in your app is bar. This class will always be applied to all the bars in your app. All bar subclasses will use the prefix – bar." }, { "code": null, "e": 24106, "s": 23834, "text": "If you want to create a header, you need to add bar-header after your main bar class. Open your www/index.html file and add the header class inside your body tag. We are adding a header to the index.html body because we want it to be available on every screen in the app." }, { "code": null, "e": 24260, "s": 24106, "text": "Since bar-header class has default (white) styling applied, we will add the title on top of it, so you can differentiate it from the rest of your screen." }, { "code": null, "e": 24333, "s": 24260, "text": "<div class = \"bar bar-header\">\n <h1 class = \"title\">Header</h1>\n</div>" }, { "code": null, "e": 24384, "s": 24333, "text": "The above code will produce the following screen −" }, { "code": null, "e": 24717, "s": 24384, "text": "If you want to style your header, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as prefix to your color class. Since we are styling the header bar, the prefix class will be bar and the color class that we want to use in this example is positive (blue)." }, { "code": null, "e": 24803, "s": 24717, "text": "<div class = \"bar bar-header bar-positive\">\n <h1 class = \"title\">Header</h1>\n</div>" }, { "code": null, "e": 24854, "s": 24803, "text": "The above code will produce the following screen −" }, { "code": null, "e": 24952, "s": 24854, "text": "You can use any of the following nine classes to give a color of your choice to your app header −" }, { "code": null, "e": 25139, "s": 24952, "text": "We can add other elements inside the header. The following code is an example to add a menu button and a home button inside a header. We will also add icons on top of our header buttons." }, { "code": null, "e": 25340, "s": 25139, "text": "<div class = \"bar bar-header bar-positive\">\n <button class = \"button icon ion-navicon\"></button>\n <h1 class = \"title\">Header Buttons</h1>\n <button class = \"button icon ion-home\"></button>\n</div>" }, { "code": null, "e": 25391, "s": 25340, "text": "The above code will produce the following screen −" }, { "code": null, "e": 25624, "s": 25391, "text": "You can create a sub header that will be located just below the header bar. The following example will show how to add a header and a sub header to your app. Here, we have styled the sub header with an \"assertive\" (red) color class." }, { "code": null, "e": 25920, "s": 25624, "text": "<div class = \"bar bar-header bar-positive\">\n <button class = \"button icon ion-navicon\"></button>\n <h1 class = \"title\">Header Buttons</h1>\n <button class = \"button icon ion-home\"></button>\n</div>\n\n<div class = \"bar bar-subheader bar-assertive\">\n <h2 class = \"title\">Sub Header</h2>\n</div>" }, { "code": null, "e": 25971, "s": 25920, "text": "The above code will produce the following screen −" }, { "code": null, "e": 26136, "s": 25971, "text": "When your route is changed to any of the app screens, you will notice that the header and the sub header are covering some content as shown in the screenshot below." }, { "code": null, "e": 26433, "s": 26136, "text": "To fix this you need to add a ‘has-header’ or a ‘has-subheader’ class to the ion-content tags of your screens. Open one of your HTML files from www/templates and add the has-subheader class to the ion-content. If you only use header in your app, you will need to add the has-header class instead." }, { "code": null, "e": 26480, "s": 26433, "text": "<ion-content class = \"padding has-subheader\">\n" }, { "code": null, "e": 26531, "s": 26480, "text": "The above code will produce the following screen −" }, { "code": null, "e": 26652, "s": 26531, "text": "Ionic footer is placed at the bottom of the app screen. Working with footers is almost the same as working with headers." }, { "code": null, "e": 26984, "s": 26652, "text": "The main class for Ionic footers is bar (the same as header). When you want to add footer to your screens, you need to add bar-footer class to your element after the main bar class. Since we want to use our footer on every screen in the app, we will add it to the body of the index.html file. We will also add title for our footer." }, { "code": null, "e": 27058, "s": 26984, "text": "<div class = \"bar bar-footer\">\n <h1 class = \"title\">Footer</h1>\n</div>\n" }, { "code": null, "e": 27109, "s": 27058, "text": "The above code will produce the following screen −" }, { "code": null, "e": 27444, "s": 27109, "text": "If you want to style your footer, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as a prefix to your color class. Since we are styling a footer bar, the prefix class will be a bar and the color class that we want to use in this example is assertive (red)." }, { "code": null, "e": 27532, "s": 27444, "text": "<div class = \"bar bar-footer bar-assertive\">\n <h1 class = \"title\">Footer</h1>\n</div>\n" }, { "code": null, "e": 27583, "s": 27532, "text": "The above code will produce the following screen −" }, { "code": null, "e": 27681, "s": 27583, "text": "You can use any of the following nine classes to give a color of your choice to your app footer −" }, { "code": null, "e": 27795, "s": 27681, "text": "Footers can contain elements inside it. Most of the time you will need to add buttons with icons inside a footer." }, { "code": null, "e": 28094, "s": 27795, "text": "The first button added will always be in the left corner. The last one will be placed on the right. The buttons in between will be grouped next to the first one on the left side of your footer. In following example, you can also notice that we use the icon class to add icons on top of the buttons." }, { "code": null, "e": 28368, "s": 28094, "text": "<div class = \"bar bar-footer bar-assertive\">\n <button class = \"button icon ion-navicon\"></button>\n <button class = \"button icon ion-home\"></button>\n <button class = \"button icon ion-star\"></button>\n <button class = \"button icon ion-checkmark-round\"></button>\n</div>" }, { "code": null, "e": 28419, "s": 28368, "text": "The above code will produce the following screen −" }, { "code": null, "e": 28494, "s": 28419, "text": "If you want to move your button to the right you can add pull-right class." }, { "code": null, "e": 28612, "s": 28494, "text": "<div class = \"bar bar-footer bar-assertive\">\n <button class = \"button icon ion-navicon pull-right\"></button>\n</div>" }, { "code": null, "e": 28663, "s": 28612, "text": "The above code will produce the following screen −" }, { "code": null, "e": 28986, "s": 28663, "text": "There are several types of buttons in the Ionic Framework and these buttons are subtly animated, which further enhances the user experience when using the app. The main class for all the button types is button. This class will always be applied to our buttons, and we will use it as a prefix when working with sub classes." }, { "code": null, "e": 29248, "s": 28986, "text": "Block buttons will always have 100% width of their parent container. They will also have a small padding applied. You will use button-block class for adding block buttons. If you want to remove padding but keep the full width, you can use the button-full class." }, { "code": null, "e": 29308, "s": 29248, "text": "Following is an example to show the usage of both classes −" }, { "code": null, "e": 29437, "s": 29308, "text": "<button class = \"button button-block\">\n button-block\n</button>\n\n<button class = \"button button-full\">\n button-full\n</button>" }, { "code": null, "e": 29488, "s": 29437, "text": "The above code will produce the following screen −" }, { "code": null, "e": 29547, "s": 29488, "text": "There are two Ionic classes for changing the button size −" }, { "code": null, "e": 29564, "s": 29547, "text": "button-small and" }, { "code": null, "e": 29581, "s": 29564, "text": "button-small and" }, { "code": null, "e": 29595, "s": 29581, "text": "button-large." }, { "code": null, "e": 29609, "s": 29595, "text": "button-large." }, { "code": null, "e": 29655, "s": 29609, "text": "Following is an example to show their usage −" }, { "code": null, "e": 29786, "s": 29655, "text": "<button class = \"button button-small\">\n button-small\n</button>\n\n<button class = \"button button-large\">\n button-large\n</button>" }, { "code": null, "e": 29837, "s": 29786, "text": "The above code will produce the following screen −" }, { "code": null, "e": 30170, "s": 29837, "text": "If you want to style your button, you just need to add appropriate color class to it. When you style your elements, you need to add your main element class as a prefix to your color class. Since we are styling the footer bar, the prefix class will be a bar and the color class that we want to use in this example is assertive (red)." }, { "code": null, "e": 30243, "s": 30170, "text": "<button class = \"button button-assertive\">\n button-assertive\n</button>" }, { "code": null, "e": 30294, "s": 30243, "text": "The above code will produce the following screen −" }, { "code": null, "e": 30393, "s": 30294, "text": "You can use any of the following nine classes to give a color of your choice to your app buttons −" }, { "code": null, "e": 30549, "s": 30393, "text": "If you want your buttons transparent, you can apply button-outline class. Buttons with this class will have an outline border and a transparent background." }, { "code": null, "e": 30681, "s": 30549, "text": "To remove the border from the button, you can use the button-clear class. The following example shows how to use these two classes." }, { "code": null, "e": 30850, "s": 30681, "text": "<button class = \"button button-assertive button-outline\">\n button-outline\n</button>\n\n<button class = \"button button-assertive button-clear\">\n button-clear\n</button>" }, { "code": null, "e": 30901, "s": 30850, "text": "The above code will produce the following screen −" }, { "code": null, "e": 31193, "s": 30901, "text": "When you want to add Icons to your buttons, the best way is to use the icon class. You can place the icon on one side of the button by using the icon-left or the icon-right. You will usually want to move your icon to one side when you have some text on top of your button as explained below." }, { "code": null, "e": 31382, "s": 31193, "text": "<button class = \"button icon ion-home\">\n</button>\n\n<button class = \"button icon icon-left ion-home\">\n Home\n</button>\n\n<button class = \"button icon icon-right ion-home\">\n Home\n</button>" }, { "code": null, "e": 31433, "s": 31382, "text": "The above code will produce the following screen −" }, { "code": null, "e": 31563, "s": 31433, "text": "If you want to group a couple of buttons together, you can use the button-bar class. The buttons will have equal size by default." }, { "code": null, "e": 31764, "s": 31563, "text": "<div class = \"button-bar\">\n <a class = \"button button-positive\">1</a>\n <a class = \"button button-assertive\">2</a>\n <a class = \"button button-energized\">3</a>\n <a class = \"button\">4</a>\n</div> " }, { "code": null, "e": 31815, "s": 31764, "text": "The above code will produce the following screen −" }, { "code": null, "e": 32143, "s": 31815, "text": "Lists are one of the most popular elements of any web or mobile application. They are usually used for displaying various information. They can be combined with other HTML elements to create different menus, tabs or to break the monotony of pure text files. Ionic framework offers different list types to make their usage easy." }, { "code": null, "e": 32523, "s": 32143, "text": "Every list is created with two elements. When you want to create a basic list your <ul> tag needs to have the list class assigned, and your <li> tag will use the item class. Another interesting thing is that you do not even need to use <ul>, <ol> and <li> tags for your lists. You can use any other elements, but the important thing is to add list and item classes appropriately." }, { "code": null, "e": 32659, "s": 32523, "text": "<div class = \"list\">\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n</div>" }, { "code": null, "e": 32710, "s": 32659, "text": "The above code will produce the following screen −" }, { "code": null, "e": 32894, "s": 32710, "text": "When you need a list to fill your own container, you can add the list-insets after your list class. This will add some margin to it and it will adjust the list size to your container." }, { "code": null, "e": 33041, "s": 32894, "text": "<div class = \"list list-inset\">\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n</div>" }, { "code": null, "e": 33092, "s": 33041, "text": "The above code will produce the following screen −" }, { "code": null, "e": 33430, "s": 33092, "text": "Dividers are used for organizing some elements into logical groups. Ionic gives us item-divider class for this. Again, like with all the other Ionic elements, we just need to add the item-divider class after the item class. Item dividers are useful as a list header, since they have stronger styling than the other list items by default." }, { "code": null, "e": 33789, "s": 33430, "text": "<div class = \"list\">\n <div class = \"item item-divider\">Item Divider 1</div>\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n\n <div class = \"item item-divider\">Item Divider 2</div>\n <div class = \"item\">Item 4</div>\n <div class = \"item\">Item 5</div>\n <div class = \"item\">Item 6</div>\n</div>" }, { "code": null, "e": 33840, "s": 33789, "text": "The above code will produce the following screen −" }, { "code": null, "e": 34210, "s": 33840, "text": "We already showed you how to add icons to your buttons. When adding icons to the list items, you need to choose what side you want to place them. There are item-icon-left and item-icon-right classes for this. You can also combine those two classes, if you want to have your Icons on both the sides. Finally, there is the item-note class to add a text note to your item." }, { "code": null, "e": 34762, "s": 34210, "text": "<div class = \"list\">\n <div class = \"item item-icon-left\">\n <i class = \"icon ion-home\"></i>\n Left side Icon\n </div>\n\n <div class = \"item item-icon-right\">\n <i class = \"icon ion-star\"></i>\n Right side Icon\n </div>\n\n <div class = \"item item-icon-left item-icon-right\">\n <i class = \"icon ion-home\"></i>\n <i class = \"icon ion-star\"></i>\n Both sides Icons\n </div>\n \n <div class = \"item item-icon-left\">\n <i class = \"icon ion-home\"></i>\n <span class = \"text-note\">Text note</span>\n </div>\n</div>" }, { "code": null, "e": 34813, "s": 34762, "text": "The above code will produce the following screen −" }, { "code": null, "e": 35217, "s": 34813, "text": "Avatars and thumbnails are similar. The main difference is that avatars are smaller than thumbnails. These thumbnails are covering most of the full height of the list item, while avatars are medium sized circle images. The classes that are used are item-avatar and item-thumbnail. You can also choose which side you want to place your avatars and thumbnails as shown in the thumbnail code example below." }, { "code": null, "e": 35459, "s": 35217, "text": "<div class = \"list\">\n <div class = \"item item-avatar\">\n <img src = \"my-image.png\">\n <h3>Avatar</h3>\n </div>\n\n <div class = \"item item-thumbnail-left\">\n <img src = \"my-image.png\">\n <h3>Thumbnail</h3>\n </div>\n</div>" }, { "code": null, "e": 35510, "s": 35459, "text": "The above code will produce the following screen −" }, { "code": null, "e": 35845, "s": 35510, "text": "Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In the previous chapter, we have discussed how to inset lists. Cards are very similar to inset lists, but they offer some additional shadowing that can influence the performance for larger lists." }, { "code": null, "e": 36228, "s": 35845, "text": "A default card can be created by adding a card class to your element. Cards are usually formed as lists with the item class. One of the most useful class is the item-text-wrap. This will help when you have too much text, so you want to wrap it inside your card. The first card in the following example does not have the item-text-wrap class assigned, but the second one is using it." }, { "code": null, "e": 36454, "s": 36228, "text": "<div class = \"card\">\n <div class = \"item\">\n This is a Ionic card without item-text-wrap class.\n </div>\n \n <div class = \"item item-text-wrap\">\n This is a Ionic card with item-text-wrap class.\n </div>\n</div>" }, { "code": null, "e": 36505, "s": 36454, "text": "The above code will produce the following screen −" }, { "code": null, "e": 36760, "s": 36505, "text": "In the previous chapter, we have already discussed how to use the item-divider class for grouping lists. This class can be very useful when working with cards to create card headers. The same class can be used for footers as shown in the following code −" }, { "code": null, "e": 36999, "s": 36760, "text": "<div class = \"card list\">\n <div class = \"item item-divider\">\n Card header\n </div>\n \n <div class = \"item item-text-wrap\">\n Card text...\n </div>\n \n <div class = \"item item-divider\">\n Card Footer\n </div>\n</div>" }, { "code": null, "e": 37050, "s": 36999, "text": "The above code will produce the following screen −" }, { "code": null, "e": 37249, "s": 37050, "text": "You can add any element on top of your card. In following example, we will show you how to use the full-image class together with the item-body to get a good-looking windowed image inside your card." }, { "code": null, "e": 37712, "s": 37249, "text": "<div class = \"card\">\n <div class = \"item item-avatar\">\n <img src = \"my-image.png\">\n <h2>Card Name</h2>\n </div>\n\n <div class = \"item item-body\">\n <img class = \"full-image\" src = \"my-image.png\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget \n pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. \n Nam tristique elit massa, quis faucibus augue finibus ac.\n </div>\n</div>" }, { "code": null, "e": 37763, "s": 37712, "text": "The above code will produce the following screen −" }, { "code": null, "e": 38001, "s": 37763, "text": "Ionic forms are mostly used for interaction with users and collecting needed info. This chapter will cover various text input forms and in our subsequent chapters, we will explain how to use other form elements using the Ionic framework." }, { "code": null, "e": 38254, "s": 38001, "text": "The best way to use forms is to use list and item as your main classes. Your app will usually consist more than one-form element, so it makes sense to organize it as a list. In the following example, you can notice that the item element is a label tag." }, { "code": null, "e": 38543, "s": 38254, "text": "You can use any other element, but a label will provide the ability to tap on any part of the element to focus your text input. You can set a placeholder that will look different from the input text and it will be hidden as soon as you start typing. You can see this in the example below." }, { "code": null, "e": 38790, "s": 38543, "text": "<div class = \"list\">\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>" }, { "code": null, "e": 38841, "s": 38790, "text": "The above code will produce the following screen −" }, { "code": null, "e": 39000, "s": 38841, "text": "Ionic offers some other options for your label. You can use the input-label class, if you want your placeholder to be on the left side when you type the text." }, { "code": null, "e": 39247, "s": 39000, "text": "<div class = \"list\">\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>" }, { "code": null, "e": 39298, "s": 39247, "text": "The above code will produce the following screen −" }, { "code": null, "e": 39675, "s": 39298, "text": "Stacked label is the other option that allows moving your label on top or the bottom of the input. To achieve this, we will add the item-stacked-label class to our label element and we need to create a new element and assign the input-label class to it. If we want it to be on top, we just need to add this element before the input tag. This is shown in the following example." }, { "code": null, "e": 39793, "s": 39675, "text": "Notice that the span tag is before the input tag. If we changed their places, it would appear below it on the screen." }, { "code": null, "e": 40176, "s": 39793, "text": "<div class = \"list\">\n <label class = \"item item-input item-stacked-label\">\n <span class = \"input-label\">Label 1</span>\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input item-stacked-label\">\n <span class = \"input-label\">Label 2</span>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>" }, { "code": null, "e": 40227, "s": 40176, "text": "The above code will produce the following screen −" }, { "code": null, "e": 40568, "s": 40227, "text": "Floating labels are the third option we can use. These labels will be hidden before we start typing. As soon the typing starts, they will appear on top of the element with nice floating animation. We can use floating labels the same way as we used stacked labels. The only difference is that this time we will use item-floating-label class." }, { "code": null, "e": 40954, "s": 40568, "text": "<div class = \"list\">\n <label class = \"item item-input item-floating-label\">\n <span class = \"input-label\"t>Label 1</span>\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n\n <label class = \"item item-input item-floating-label\">\n <span class = \"input-label\">Label 2</span>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n</div>" }, { "code": null, "e": 41005, "s": 40954, "text": "The above code will produce the following screen −" }, { "code": null, "e": 41241, "s": 41005, "text": "In our last chapter, we discussed how to inset Ionic elements. You can also inset an input by adding the item-input-inset class to your item and the item-input-wrapper to your label. A Wrapper will add additional styling to your label." }, { "code": null, "e": 41412, "s": 41241, "text": "If you add some other elements next to your label, the label size will adjust to accommodate the new element. You can also add elements inside your label (usually icons)." }, { "code": null, "e": 41698, "s": 41412, "text": "The following example shows two inset inputs. The first one has a button next to the label, and the second one has an icon inside it. We used the placeholder-icon class to make the icon with the same color as the placeholder text. Without it, the icon would use the color of the label." }, { "code": null, "e": 42188, "s": 41698, "text": "<div class = \"list\">\n <div class = \"item item-input-inset\">\n <label class = \"item item-input-wrapper\">\t\t\n <input type = \"text\" placeholder = \"Placeholder 1\" />\n </label>\n <button class = \"button\">button</button>\n </div>\n\n <div class = \"item item-input-inset\">\n <label class = \"item item-input-wrapper\">\n <i class = \"icon ion-edit placeholder-icon\"></i>\n <input type = \"text\" placeholder = \"Placeholder 2\" />\n </label>\n </div>\n</div>" }, { "code": null, "e": 42239, "s": 42188, "text": "The above code will produce the following screen −" }, { "code": null, "e": 42453, "s": 42239, "text": "Sometimes there are two options available for the users. The most efficient way to handle this situation is through toggle forms. Ionic gives us classes for toggle elements that are animated and easy to implement." }, { "code": null, "e": 42627, "s": 42453, "text": "Toggle can be implemented using two Ionic classes. First, we need to create a label for the same reason we explained in the previous chapter and assign a toggle class to it." }, { "code": null, "e": 42894, "s": 42627, "text": "Inside our label will be created . You will notice two more ionic classes used in the following example. The track class will add background styling to our checkbox and color animation when the toggle is tapped. The handle class is used to add a circle button to it." }, { "code": null, "e": 42989, "s": 42894, "text": "The following example shows two toggle forms. The first one is checked, the second one is not." }, { "code": null, "e": 43266, "s": 42989, "text": "<label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n</label>\n\n<br>\n\n<label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n</label>" }, { "code": null, "e": 43317, "s": 43266, "text": "The above code will produce the following screen −" }, { "code": null, "e": 43606, "s": 43317, "text": "Most of the time when you want to add more than one element of the same kind in Ionic, the best way is to use list items. The class that is used for multiple toggles is the item-toggle. The next example shows how to create a list for toggles. The first one and the second one are checked." }, { "code": null, "e": 44555, "s": 43606, "text": "<ul class = \"list\">\n <li class = \"item item-toggle\">\n Toggle 1\n <label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle 2\n <label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle 3\n <label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle 4\n <label class = \"toggle\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n</ul>" }, { "code": null, "e": 44606, "s": 44555, "text": "The above code will produce the following screen −" }, { "code": null, "e": 44805, "s": 44606, "text": "All the Ionic color classes can be applied to the toggle element. The Prefix will be the toggle. We will apply this to the label element. The following example shows all the colors that are applied." }, { "code": null, "e": 47090, "s": 44805, "text": "<ul class = \"list\">\n <li class = \"item item-toggle\">\n Toggle Light\n <label class = \"toggle toggle-light\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Stable\n <label class = \"toggle toggle-stable\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Positive\n <label class = \"toggle toggle-positive\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Calm\n <label class = \"toggle toggle-calm\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Balanced\n <label class = \"toggle toggle-balanced\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Energized\n <label class = \"toggle toggle-energized\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Assertive\n <label class = \"toggle toggle-assertive\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Royal\n <label class = \"toggle toggle-royal\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n\n <li class = \"item item-toggle\">\n Toggle Dark\n <label class = \"toggle toggle-dark\">\n <input type = \"checkbox\" />\n <div class = \"track\">\n <div class = \"handle\"></div>\n </div>\n </label>\n </li>\n</ul>" }, { "code": null, "e": 47141, "s": 47090, "text": "The above code will produce the following screen −" }, { "code": null, "e": 47255, "s": 47141, "text": "Ionic checkbox is almost the same as toggle. These two are styled differently but are used for the same purposes." }, { "code": null, "e": 47452, "s": 47255, "text": "When creating a checkbox form, you need to add the checkbox class name to both label and the input elements. The following example shows two simple checkboxes, one is checked and the other is not." }, { "code": null, "e": 47583, "s": 47452, "text": "<label class = \"checkbox\">\n <input type = \"checkbox\">\n</label>\n\n<label class = \"checkbox\">\n <input type = \"checkbox\">\n</label>" }, { "code": null, "e": 47634, "s": 47583, "text": "The above code will produce the following screen −" }, { "code": null, "e": 47761, "s": 47634, "text": "As we already showed, the list will be used for multiple elements. Now we will use the item-checkbox class for each list item." }, { "code": null, "e": 48382, "s": 47761, "text": "<ul class = \"list\">\n <li class = \"item item-checkbox\">\n Checkbox 1\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox\">\n Checkbox 2\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox\">\n Checkbox e\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox\">\n Checkbox 4\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n</ul>" }, { "code": null, "e": 48433, "s": 48382, "text": "The above code will produce the following screen −" }, { "code": null, "e": 48641, "s": 48433, "text": "When you want to style a checkbox, you need to apply any Ionic color class with the checkbox prefix. Check the following example to see how it looks like. We will use the list of checkboxes for this example." }, { "code": null, "e": 50162, "s": 48641, "text": "<ul class = \"list\">\n <li class = \"item item-checkbox checkbox-light\">\n Checkbox 1\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-stable\">\n Checkbox 2\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-positive\">\n Checkbox 3\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-calm\">\n Checkbox 4\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-balanced\">\n Checkbox 5\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-energized\">\n Checkbox 6\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-assertive\">\n Checkbox 7\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-royal\">\n Checkbox 8\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n\n <li class = \"item item-checkbox checkbox-dark\">\n Checkbox 9\n <label class = \"checkbox\">\n <input type = \"checkbox\" />\n </label>\n </li>\n</ul>" }, { "code": null, "e": 50213, "s": 50162, "text": "The above code will produce the following screen −" }, { "code": null, "e": 50499, "s": 50213, "text": "Radio buttons are another form of an element, which we will be covering in this chapter. The difference between radio buttons from toggle and checkbox forms is that when using the former, you choose only one radio button from the list. As the latter allows you to choose more than one." }, { "code": null, "e": 51080, "s": 50499, "text": "Since there will always be more than one radio button to choose from, the best way is to create a list. We did this whenever we wanted multiple elements. The list item class will be item-radio. Again, we will use label for this as we have used with all the other forms. Input will have the name attribute. This attribute will group all the buttons that you want to use as a possible choice. The item-content class is used to display options clearly. At the end, we will use the radio-icon class to add the checkmark icon that will be used to mark the option that the user chooses." }, { "code": null, "e": 51165, "s": 51080, "text": "In the following example, there are four radio buttons and the second one is chosen." }, { "code": null, "e": 52040, "s": 51165, "text": "<div class = \"list\">\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 1\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 2\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 3\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 4\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n</div>" }, { "code": null, "e": 52091, "s": 52040, "text": "The above code will produce the following screen −" }, { "code": null, "e": 52280, "s": 52091, "text": "Sometimes you want to create more than one group. This is what the name attribute is made for; the following example will group the first two and the last two buttons as two option groups." }, { "code": null, "e": 52438, "s": 52280, "text": "We will use the item-divider class to separate two groups. Notice that the first group has the name attribute equal to group1 and the second one uses group2." }, { "code": null, "e": 53436, "s": 52438, "text": "<div class = \"list\">\n <div class = \" item item-divider\">\n Group1\n </div>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 1\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group1\" />\n <div class = \"item-content\">\n Choice 2\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <div class = \"item item-divider\">\n Group2\n </div>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group2\" />\n <div class = \"item-content\">\n Choice 3\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n\n <label class = \"item item-radio\">\n <input type = \"radio\" name = \"group2\" />\n <div class = \"item-content\">\n Choice 4\n </div>\n <i class = \"radio-icon ion-checkmark\"></i>\n </label>\n</div>" }, { "code": null, "e": 53487, "s": 53436, "text": "The above code will produce the following screen −" }, { "code": null, "e": 53682, "s": 53487, "text": "Ionic range is used to choose and display the level of something. It will represent the actual value in co-relation to maximal and minimal value. Ionic offers a simple way of working with Range." }, { "code": null, "e": 53978, "s": 53682, "text": "Range is used as an inside item element. The class that is used is range. We will place this class after the item class. This will prepare a container where the range will be placed. After creating a container, we need to add input and assign the range type to it and the name attribute as well." }, { "code": null, "e": 54055, "s": 53978, "text": "<div class = \"item range\">\n <input type = \"range\" name = \"range1\">\n</div>\n" }, { "code": null, "e": 54106, "s": 54055, "text": "The above code will produce the following screen −" }, { "code": null, "e": 54277, "s": 54106, "text": "Range will usually require icons to display the data clearly. We just need to add icons before and after the range input to place them on both sides of the range element." }, { "code": null, "e": 54436, "s": 54277, "text": "<div class = \"item range\">\n <i class = \"icon ion-volume-low\"></i>\n <input type = \"range\" name = \"volume\">\n <i class = \"icon ion-volume-high\"></i>\n</div>" }, { "code": null, "e": 54487, "s": 54436, "text": "The above code will produce the following screen −" }, { "code": null, "e": 54664, "s": 54487, "text": "Our next example will show you how to style Range with Ionic colors. The color classes will use a range prefix. We will create a list with nine ranges and style it differently." }, { "code": null, "e": 55594, "s": 54664, "text": "<div class = \"list\">\n <div class = \"item range range-light\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-stable\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-positive\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-calm\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-balanced\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-energized\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-assertive\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-royal\">\n <input type = \"range\" name = \"volume\">\n </div>\n\t\n <div class = \"item range range-dark\">\n <input type = \"range\" name = \"volume\">\n </div>\n</div>" }, { "code": null, "e": 55645, "s": 55594, "text": "The above code will produce the following screen −" }, { "code": null, "e": 55836, "s": 55645, "text": "Ionic Select will create a simple menu with select options for the user to choose. This Select Menu will look differently on different platforms, since its styling is handled by the browser." }, { "code": null, "e": 56235, "s": 55836, "text": "First, we will create a label and add the item-input and the item-select classes. The second class will add additional styling to the select form and then we will add the input-label class inside that will be used to add a name to our select element. We will also add select with option inside. This is regular HTML5 select element. The following example is showing Ionic Select with three options." }, { "code": null, "e": 56476, "s": 56235, "text": "<label class = \"item item-input item-select\">\n <div class = \"input-label\">\n Select\n </div>\n\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n</label>" }, { "code": null, "e": 56527, "s": 56476, "text": "The above code will produce the following screen −" }, { "code": null, "e": 56765, "s": 56527, "text": "The following example will show you how to apply styling to select. We are creating a list with nine differently styled select elements using Ionic colors. Since we are using list with items, item will be the prefix to the color classes." }, { "code": null, "e": 59361, "s": 56765, "text": "<div class = \"list\">\n <label class = \"item item-input item-select item-light\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-stable\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-positive\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-calm\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-balanced\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-energized\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-assertive\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-royal\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n\n <label class = \"item item-input item-select item-dark\">\n <div class = \"input-label\">\n Select\n </div>\n\t\t\n <select>\n <option>Option 1</option>\n <option selected>Option 2</option>\n <option>Option 3</option>\n </select>\n </label>\n</div>" }, { "code": null, "e": 59412, "s": 59361, "text": "The above code will produce the following screen −" }, { "code": null, "e": 59748, "s": 59412, "text": "Ionic tabs are most of the time used for mobile navigation. Styling is optimized for different platforms. This means that on android devices, tabs will be placed at the top of the screen, while on IOS it will be at the bottom. There are different ways of creating tabs. We will understand in detail, how to create tabs in this chapter." }, { "code": null, "e": 60018, "s": 59748, "text": "Simple Tabs menu can be created with a tabs class. For the inside element that is using this class, we need to add tab-item elements. Since tabs are usually used for navigation, we will use <a> tags for tab items. The following example is showing a menu with four tabs." }, { "code": null, "e": 60187, "s": 60018, "text": "<div class = \"tabs\">\n <a class = \"tab-item\">\n Tab 1\n </a>\n\t\n <a class = \"tab-item\">\n Tab 2\n </a>\n\n <a class = \"tab-item\">\n Tab 3\n </a>\n</div>" }, { "code": null, "e": 60238, "s": 60187, "text": "The above code will produce the following screen −" }, { "code": null, "e": 60456, "s": 60238, "text": "Ionic provides classes for adding icons to tabs. If you want your tabs to have icons without any text, a tabs-icon-only class should be added after the tabs class. Of course, you need to add icons you want to display." }, { "code": null, "e": 60721, "s": 60456, "text": "<div class = \"tabs tabs-icon-only\">\n <a class = \"tab-item\">\n <i class = \"icon ion-home\"></i>\n </a>\n\t\n <a class = \"tab-item\">\n <i class = \"icon ion-star\"></i>\n </a>\n\t\n <a class = \"tab-item\">\n <i class = \"icon ion-planet\"></i>\n </a>\n</div>" }, { "code": null, "e": 60772, "s": 60721, "text": "The above code will produce the following screen −" }, { "code": null, "e": 61099, "s": 60772, "text": "You can also add icons and text together. The tabs-icon-top and tabs-icon-left are classes that will place the icon above or on the left side respectively. Implementation is the same as the example given above, we will just add a new class and text that we want to use. The following example shows icons placed above the text." }, { "code": null, "e": 61399, "s": 61099, "text": "<div class = \"tabs tabs-icon-top\">\n <a class = \"tab-item\">\n <i class = \"icon ion-home\"></i>\n Tab 1\n </a>\n\t\n <a class = \"tab-item\">\n <i class = \"icon ion-star\"></i>\n Tab 2\n </a>\n\t\n <a class = \"tab-item\">\n <i class = \"icon ion-planet\"></i>\n Tab 3\n </a>\n</div>" }, { "code": null, "e": 61450, "s": 61399, "text": "The above code will produce the following screen −" }, { "code": null, "e": 61678, "s": 61450, "text": "Striped Tabs can be created by adding a container around our tabs with the tabs-striped class. This class allows the usage of the tabs-background and the tabs-color prefixes for adding some of the Ionic colors to the tabs menu." }, { "code": null, "e": 61950, "s": 61678, "text": "In the following example, we will use the tabs-background-positive (blue) class to style the background of our menu, and the tabs-color-light (white) class to style the tab icons. Notice the difference between the second tab that is active and the other two that are not." }, { "code": null, "e": 62320, "s": 61950, "text": "<div class = \"tabs-striped tabs-background-positive tabs-color-light\">\n <div class = \"tabs\">\n <a class = \"tab-item\">\n <i class = \"icon ion-home\"></i>\n </a>\n\t\t\n <a class = \"tab-item active\">\n <i class = \"icon ion-star\"></i>\n </a>\n\t\t\n <a class = \"tab-item\">\n <i class = \"icon ion-planet\"></i>\n </a>\n </div>\n</div>" }, { "code": null, "e": 62371, "s": 62320, "text": "The above code will produce the following screen −" }, { "code": null, "e": 62502, "s": 62371, "text": "Working with the Ionic Grid System is straightforward. There are two main classes – row for working with rows and col for columns." }, { "code": null, "e": 62678, "s": 62502, "text": "You can choose as many columns or rows you want. All of them will adjust its size to accommodate the available space, although you can change this behavior to suit your needs." }, { "code": null, "e": 62815, "s": 62678, "text": "NOTE − All examples in this tutorial will have borders applied to our grid to be able to display it in a way that is easy to understand." }, { "code": null, "e": 63064, "s": 62815, "text": "The following example shows how to use the col and the row classes. We will create two rows. The first row will have five columns and the second one will have only three. Notice how the width of the columns is different in the first and second row." }, { "code": null, "e": 63391, "s": 63064, "text": "<div class = \"row\">\n <div class = \"col\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n <div class = \"col\">col 4</div>\n <div class = \"col\">col 5</div>\n</div>\n\n<div class = \"row\">\n <div class = \"col\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n</div>" }, { "code": null, "e": 63442, "s": 63391, "text": "The above code will produce the following screen −" }, { "code": null, "e": 63773, "s": 63442, "text": "Sometimes you do not want to leave the column sizes automatically assigned. If this is the case, you can choose the col prefix followed by a number that will represent a percentage of the row width. This will apply only to the column with a specific size applied. The other columns will adjust to the available space that is left." }, { "code": null, "e": 63894, "s": 63773, "text": "In the following example, the first column will use 50 percent of the full width and the others will adjust accordingly." }, { "code": null, "e": 64235, "s": 63894, "text": "<div class = \"row\">\n <div class = \"col col-50\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n <div class = \"col\">col 4</div>\n <div class = \"col\">col 5</div>\n</div>\n\n<div class = \"row\">\n <div class = \"col col-50\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n</div>" }, { "code": null, "e": 64282, "s": 64235, "text": "The above code will produce following screen −" }, { "code": null, "e": 64375, "s": 64282, "text": "The following table shows the available percentage options that Ionic grid system provides −" }, { "code": null, "e": 64684, "s": 64375, "text": "The columns can be offset from the left. It works the same for the specific size of the columns. This time the prefix will be col-offset and then we will use the same percentage numbers showed in the table above. The following example shows how can we offset the second column of both the rows by 25 percent." }, { "code": null, "e": 65039, "s": 64684, "text": "<div class = \"row\">\n <div class = \"col\">col 1</div>\n <div class = \"col col-offset-25\">col 2</div>\n <div class = \"col\">col 3</div>\n <div class = \"col\">col 4</div>\n <div class = \"col\">col 5</div>\n</div>\n\n<div class = \"row\">\n <div class = \"col\">col 1</div>\n <div class = \"col col-offset-25\">col 2</div>\n <div class = \"col\">col 3</div>\n</div>" }, { "code": null, "e": 65090, "s": 65039, "text": "The above code will produce the following screen −" }, { "code": null, "e": 65340, "s": 65090, "text": "You can also vertically align the columns inside a row. There are three classes, which can be used, namely – top, center and the bottom class with the col prefix. The following code shows how to place vertically the first three columns of both rows." }, { "code": null, "e": 65467, "s": 65340, "text": "NOTE − In the example that follows we added “.col {height: 120px}” to our CSS to show you the vertical placing of the columns." }, { "code": null, "e": 65854, "s": 65467, "text": "<div class = \"row\">\n <div class = \"col col-top\">col 1</div>\n <div class = \"col col-center\">col 2</div>\n <div class = \"col col-bottom\">col 3</div>\n <div class = \"col\">col 4</div>\n <div class = \"col\">col 5</div>\n</div>\n\n<div class = \"row\">\n <div class = \"col col-top\">col 1</div>\n <div class = \"col col-center\">col 2</div>\n <div class = \"col col-bottom\">col 3</div>\n</div>" }, { "code": null, "e": 65905, "s": 65854, "text": "The above code will produce the following screen −" }, { "code": null, "e": 66293, "s": 65905, "text": "The Ionic Grid can also be used for a responsive layout. There are three classes available. The responsive-sm class will collapse columns into a single row when the viewport is smaller than a landscape phone. The responsive-md class will be applied when viewport is smaller than a portrait tablet. The responsive-lg class will be applied when viewport is smaller than a landscape tablet." }, { "code": null, "e": 66488, "s": 66293, "text": "The first image after the following example shows how the responsive-sm class looks on a Mobile device and the second one shows how the same responsive grid looks differently on a Tablet device." }, { "code": null, "e": 66850, "s": 66488, "text": "<div class = \"row responsive-sm\">\n <div class = \"col col-25\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n <div class = \"col\">col 4</div>\n <div class = \"col\">col 5</div>\n</div>\n\n<div class = \"row responsive-sm\">\n <div class = \"col\">col 1</div>\n <div class = \"col\">col 2</div>\n <div class = \"col\">col 3</div>\n</div>" }, { "code": null, "e": 67177, "s": 66850, "text": "There are more than 700 premium icons provided by Ionic. There are also different sets of icons provided for Android and IOS. You can find almost anything you need but you are not bound to use them, if you do not want to. You can use your own custom icons or any other icon set instead. You can check all the Ionic icons here." }, { "code": null, "e": 67524, "s": 67177, "text": "If you want to use Ionic icons find the icon you need on the page (https://ionicons.com/). When you are adding Ionic elements, you always add the main class first and then you add the subclass you want. The main class for all icons is icon. The Subclass is the name of the icon you want. We will add six icons in our example that is given below −" }, { "code": null, "e": 67772, "s": 67524, "text": "<i class = \"icon icon ion-happy-outline\"></i>\n<i class = \"icon icon ion-star\"></i>\n<i class = \"icon icon ion-compass\"></i>\n<i class = \"icon icon ion-planet\"></i>\n<i class = \"icon icon ion-ios-analytics\"></i>\n<i class = \"icon icon ion-ios-eye\"></i>" }, { "code": null, "e": 67823, "s": 67772, "text": "The above code will produce the following screen −" }, { "code": null, "e": 67914, "s": 67823, "text": "The size of these icons can be changed with the font-size property in your Ionic CSS file." }, { "code": null, "e": 67944, "s": 67914, "text": ".icon {\n font-size: 50px;\n}" }, { "code": null, "e": 68041, "s": 67944, "text": "Once the icon size is setup, the same code will produce the following screenshot as the output −" }, { "code": null, "e": 68276, "s": 68041, "text": "Ionic offers an easy way to add padding to elements. There are couple of classes that can be used and all of them will add 10px between border of element and its content. The following table displays all the available padding classes." }, { "code": null, "e": 68595, "s": 68276, "text": "When you want to apply some padding to your element, you just need to assign one of the classes from the table above. The following example shows two block buttons. The first one is using the padding class and the second one does not. You will notice that the first button is larger, since it has 10px padding applied." }, { "code": null, "e": 68705, "s": 68595, "text": "<div class = \"button button-block padding\">Padding</div>\n<div class = \"button button-block\">No padding</div>\n" }, { "code": null, "e": 68756, "s": 68705, "text": "The above code will produce the following screen −" }, { "code": null, "e": 68896, "s": 68756, "text": "The Action Sheet is an Ionic service that will trigger a slide up pane on the bottom of the screen, which you can use for various purposes." }, { "code": null, "e": 69200, "s": 68896, "text": "In the following example, we will show you how to use the Ionic action sheet. First we will inject $ionicActionSheet service as a dependency to our controller, then we will create $scope.showActionSheet() function, and lastly we will create a button in our HTML template to call the function we created." }, { "code": null, "e": 70004, "s": 69200, "text": ".controller('myCtrl', function($scope, $ionicActionSheet) {\n $scope.triggerActionSheet = function() {\n // Show the action sheet\n var showActionSheet = $ionicActionSheet.show({\n buttons: [\n { text: 'Edit 1' },\n { text: 'Edit 2' }\n ],\n\t\t\t\n destructiveText: 'Delete',\n titleText: 'Action Sheet',\n cancelText: 'Cancel',\n\t\t\t\n cancel: function() {\n // add cancel code...\n },\n\t\t\t\n buttonClicked: function(index) {\n if(index === 0) {\n // add edit 1 code\n }\n\t\t\t\t\n if(index === 1) {\n // add edit 2 code\n }\n },\n\t\t\t\n destructiveButtonClicked: function() {\n // add delete code..\n }\n });\n };\n})" }, { "code": null, "e": 70059, "s": 70004, "text": "<button class = \"button\">Action Sheet Button</button>\n" }, { "code": null, "e": 70416, "s": 70059, "text": "When we tap the button, it will trigger the $ionicActionSheet.show function and the Action Sheet will appear. You can create your own functions that will be called when one of the options is taped. The cancel function will close the pane, but you can add some other behavior, which will be called when the cancel option is tapped before the pane is closed." }, { "code": null, "e": 70744, "s": 70416, "text": "The buttonClicked function is the place where you can write the code that will be called when one of the edit options is tapped. We can keep track of multiple buttons by using the index parameter. The destructiveButtonCLicked is a function that will be triggered when the delete option is tapped. This option is red by default." }, { "code": null, "e": 70864, "s": 70744, "text": "The $ionicActionSheet.show() method has some other useful parameters. You can check all of them in the following table." }, { "code": null, "e": 71182, "s": 70864, "text": "The Ionic Backdrop will overlay the content of the screen when applied. It will appear below other overlays (popup, loading, etc...). There are two methods that can be used for managing backdrop service. The $ionicBackdrop.retain() will apply backdrop over the components, and $ionicBackdrop.release() will remove it." }, { "code": null, "e": 71549, "s": 71182, "text": "The following example shows how to use backdrop. We are adding $ionicBackdrop as a dependency to the controller, then creating the $scope.showBackdrop() function that will call the retain method immediately. Then, after three seconds, it will call the release method. We are using $timeout for the release method, so we need to add it as a controller dependency too." }, { "code": null, "e": 71776, "s": 71549, "text": ".controller('myCtrl', function($scope, $ionicBackdrop, $timeout) {\n $scope.showBackdrop = function() {\n $ionicBackdrop.retain();\n\t\t\n $timeout(function() {\n $ionicBackdrop.release();\n }, 3000);\n };\n})" }, { "code": null, "e": 71872, "s": 71776, "text": "You will notice how the screen is darker in the following image, since the backdrop is applied." }, { "code": null, "e": 72228, "s": 71872, "text": "Almost every mobile app contains some fundamental elements. Usually these elements include a header and a footer, which will cover the top and the bottom part of the screen. All the other elements will be placed between these two. Ionic provide ion-content element that serves as a container, which will wrap all the other elements that we want to create." }, { "code": null, "e": 72268, "s": 72228, "text": "Let us consider the following example −" }, { "code": null, "e": 72676, "s": 72268, "text": "<div class = \"bar bar-header\"> \n <h1 class = \"title\">Header</h1> \n</div>\n\n<div class = \"list\"> \n <label class = \"item item-input\"> \n <input type = \"text\" placeholder = \"Placeholder 1\" /> \n </label>\n \n <label class = \"item item-input\"> \n <input type = \"text\" placeholder = \"Placeholder 2\" /> \n </label> \n</div>\n\n<div class = \"bar bar-footer\"> \n <h1 class = \"title\">Footer</h1> \n</div>" }, { "code": null, "e": 72811, "s": 72676, "text": "In this chapter, we will understand what JavaScript forms are and will learn what a JavaScript checkbox, radio buttons and toggle are." }, { "code": null, "e": 73232, "s": 72811, "text": "Let us see how to use the Ionic JavaScript checkbox. Firstly, we need to create an ion-checkbox element in the HTML file. Inside this, we will assign an ng-model attribute that will be connected to the angular $scope. You will notice that we are using a dot when defining the value of a model even though it would work without it. This will allow us to keep the link between the child and the parent scopes at all times." }, { "code": null, "e": 73400, "s": 73232, "text": "This is very important as it helps to avoid some issues that could happen in the future. After we create the element, we will bind its value using angular expressions." }, { "code": null, "e": 73669, "s": 73400, "text": "<ion-checkbox ng-model = \"checkboxModel.value1\">Checkbox 1</ion-checkbox>\n<ion-checkbox ng-model = \"checkboxModel.value2\">Checkbox 2</ion-checkbox>\n\n<p>Checkbox 1 value is: <b>{{checkboxModel.value1}}</b></p>\n<p>Checkbox 2 value is: <b>{{checkboxModel.value2}}</b></p>" }, { "code": null, "e": 73820, "s": 73669, "text": "Next, we need to assign values to our model inside the controller. The values we will use are false, since we want to start with unchecked checkboxes." }, { "code": null, "e": 73885, "s": 73820, "text": "$scope.checkboxModel = {\n value1 : false,\n value2 : false\n};" }, { "code": null, "e": 73936, "s": 73885, "text": "The above code will produce the following screen −" }, { "code": null, "e": 74071, "s": 73936, "text": "Now, when we tap the checkbox elements, it will automatically change their model value to “true” as shown in the following screenshot." }, { "code": null, "e": 74364, "s": 74071, "text": "To start with, we should create three ion-radio elements in our HTML and assign the ng-model and the ng-value to it. After that, we will display the chosen value with angular expression. We will start by unchecking all the three radioelements, so the value will not be assigned to our screen." }, { "code": null, "e": 74644, "s": 74364, "text": "<ion-radio ng-model = \"radioModel.value\" ng-value = \"1\">Radio 1</ion-radio>\n<ion-radio ng-model = \"radioModel.value\" ng-value = \"2\">Radio 2</ion-radio>\n<ion-radio ng-model = \"radioModel.value\" ng-value = \"3\">Radio 3</ion-radio>\n\n<p>Radio value is: <b>{{radioModel.value}}</b></p>" }, { "code": null, "e": 74695, "s": 74644, "text": "The above code will produce the following screen −" }, { "code": null, "e": 74774, "s": 74695, "text": "When we tap on the second checkbox element, the value will change accordingly." }, { "code": null, "e": 75024, "s": 74774, "text": "You will notice that toggle is similar to checkbox. We will follow the same steps as we did with our checkbox. In the HTML file, first we will create ion-toggle elements, then assign the ng-model value and then bind expression values of to our view." }, { "code": null, "e": 75391, "s": 75024, "text": "<ion-toggle ng-model = \"toggleModel.value1\">Toggle 1</ion-toggle>\n<ion-toggle ng-model = \"toggleModel.value2\">Toggle 2</ion-toggle>\n<ion-toggle ng-model = \"toggleModel.value3\">Toggle 3</ion-toggle>\n\n<p>Toggle value 1 is: <b>{{toggleModel.value1}}</b></p>\n<p>Toggle value 2 is: <b>{{toggleModel.value2}}</b></p>\n<p>Toggle value 3 is: <b>{{toggleModel.value3}}</b></p>" }, { "code": null, "e": 75565, "s": 75391, "text": "Next, we will assign values to $scope.toggleModel in our controller. Since, toggle uses Boolean values, we will assign true to the first element and false to the other two.\n" }, { "code": null, "e": 75646, "s": 75565, "text": "$scope.toggleModel = {\n value1 : true,\n value2 : false,\n value3 : false\n};" }, { "code": null, "e": 75697, "s": 75646, "text": "The above code will produce the following screen −" }, { "code": null, "e": 75794, "s": 75697, "text": "Now we will tap on second and third toggle to show you how the values change from false to true." }, { "code": null, "e": 75911, "s": 75794, "text": "Various Ionic events can be used to add interactivity with users. The following table explains all the Ionic events." }, { "code": null, "e": 76183, "s": 75911, "text": "Since all the Ionic events can be used the same way, we will show you how to use the on-touch event and you can just apply the same principles to the other events. To start with, we will create a button and assign an on-touch event, which will call the onTouchFunction()." }, { "code": null, "e": 76251, "s": 76183, "text": "<button on-touch = \"onTouchFunction()\" class=\"button\">Test</button>" }, { "code": null, "e": 76310, "s": 76251, "text": "Then we will create that function in our controller scope." }, { "code": null, "e": 76372, "s": 76310, "text": "$scope.onTouchFunction = function() {\n // Do something...\n}" }, { "code": null, "e": 76439, "s": 76372, "text": "Now, when touch event occurs the onTouchFunction() will be called." }, { "code": null, "e": 76499, "s": 76439, "text": "This is the Ionic directive, which will add the header bar." }, { "code": null, "e": 76733, "s": 76499, "text": "To create a JavaScript header bar, we need to apply the ion-header-bar directive in the HTML file. Since the default header is white, we will add title, so it will be showed on white background. We will add it to our index.html file." }, { "code": null, "e": 76803, "s": 76733, "text": "<ion-header-bar>\n <h1 class = \"title\">Title!</h1>\n</ion-header-bar>" }, { "code": null, "e": 76854, "s": 76803, "text": "The above code will produce the following screen −" }, { "code": null, "e": 77239, "s": 76854, "text": "Just like the CSS Header Bar, the JavaScript counterpart can be styled in a similar fashion. To apply color, we need to add a color class with a bar prefix. Therefore, if we want to use a blue header, we will add a bar-positive class. We can also move the title to one side of the screen by adding the align-title attribute. The values for this attribute can be center, left or right." }, { "code": null, "e": 77353, "s": 77239, "text": "<ion-header-bar align-title = \"left\" class = \"bar-positive\">\n <h1 class = \"title\">Title!</h1>\n</ion-header-bar>" }, { "code": null, "e": 77404, "s": 77353, "text": "The above code will produce the following screen −" }, { "code": null, "e": 77631, "s": 77404, "text": "You will usually want to add some elements to your header. The following example shows how to place a button on the left side and an icon to the right side of the ion-header-bar. You can also add other elements to your header." }, { "code": null, "e": 77904, "s": 77631, "text": "<ion-header-bar class = \"bar-positive\">\n <div class = \"buttons\">\n <button class = \"button\">Button</button>\n </div>\n \n <h1 class = \"title\">Title!</h1>\n <div class = \"buttons\">\n <button class = \"button icon ion-home\"></button>\n </div>\n</ion-header-bar>" }, { "code": null, "e": 77955, "s": 77904, "text": "The above code will produce the following screen −" }, { "code": null, "e": 78110, "s": 77955, "text": "A Sub header is created when a bar-subheader class is added to the ion-header-bar. We will add a bar-assertive class to apply red color to our sub header." }, { "code": null, "e": 78495, "s": 78110, "text": "<ion-header-bar class = \"bar-positive\">\n <div class = \"buttons\">\n <button class = \"button\">Button</button>\n </div>\n \n <h1 class = \"title\">Title!</h1>\n <div class = \"buttons\">\n <button class = \"button icon ion-home\"></button>\n </div>\n</ion-header-bar>\n\n<ion-header-bar class = \"bar-subheader bar-assertive\">\n <h1 class = \"title\">Subheader</h1>\n</ion-header-bar>" }, { "code": null, "e": 78546, "s": 78495, "text": "The above code will produce the following screen −" }, { "code": null, "e": 78612, "s": 78546, "text": "This directive will add a footer bar at the bottom of the screen." }, { "code": null, "e": 78958, "s": 78612, "text": "The Ionic footer can be added by applying an ion-footer-bar class. Working with it is same as working with header. We can add a title and place it on the left, center or right side of the screen by using the align-title attribute. With the prefix bar, we can use the Ionic colors. Let us create a red colored footer with the title in the center." }, { "code": null, "e": 79075, "s": 78958, "text": "<ion-footer-bar align-title = \"center\" class = \"bar-assertive\">\n <h1 class = \"title\">Title!</h1>\n</ion-footer-bar>" }, { "code": null, "e": 79126, "s": 79075, "text": "The above code will produce the following screen −" }, { "code": null, "e": 79273, "s": 79126, "text": "We can add buttons icons or other elements to the ion-footer-bar and their styling will be applied. Let us add a button and an Icon to our footer." }, { "code": null, "e": 79547, "s": 79273, "text": "<ion-footer-bar class = \"bar-assertive\">\n <div class = \"buttons\">\n <button class = \"button\">Button</button>\n </div>\n \n <h1 class = \"title\">Footer</h1>\n\n <div class = \"buttons\">\n <button class = \"button icon ion-home\"></button>\n </div>\n</ion-footer-bar>" }, { "code": null, "e": 79597, "s": 79547, "text": "The above code will produce the following screen−" }, { "code": null, "e": 79797, "s": 79597, "text": "We showed you how to use a sub header. The same way a sub footer can be created. It will be located above the footer bar. All we need to do is add a bar-subfooter class to our ion-footer-bar element." }, { "code": null, "e": 79900, "s": 79797, "text": "In example that follows, we will add the sub-footer above the footer bar, which we previously created." }, { "code": null, "e": 80313, "s": 79900, "text": "<ion-footer-bar class = \"bar-subfooter bar-positive\">\n <h1 class = \"title\">Sub Footer</h1>\n</ion-footer-bar>\n\n<ion-footer-bar class = \"bar-assertive\">\n <div class = \"buttons\">\n <button class = \"button\">Button</button>\n </div>\n \n <h1 class = \"title\">Footer</h1>\n\n <div class = \"buttons\" ng-click = \"doSomething()\">\n <button class = \"button icon ion-home\"></button>\n </div>\n</ion-footer-bar>" }, { "code": null, "e": 80364, "s": 80313, "text": "The above code will produce the following screen −" }, { "code": null, "e": 80495, "s": 80364, "text": "Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open the keyboard." }, { "code": null, "e": 80813, "s": 80495, "text": "There are some functionalities, which the developers can adjust while working with the Ionic keyboard. When you want to hide some elements while the keyboard is open, you can use the hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when the keyboard is open." }, { "code": null, "e": 80987, "s": 80813, "text": "<label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Input 1\">\n</label>\n\n<button class = \"button button-block hide-on-keyboard-open\">\n button\n</button>" }, { "code": null, "e": 81038, "s": 80987, "text": "The above code will produce the following screen −" }, { "code": null, "e": 81147, "s": 81038, "text": "Now, when we tap on the input field, the keyboard will open automatically and the button will become hidden." }, { "code": null, "e": 81356, "s": 81147, "text": "A nice feature of Ionic is that it will adjust elements on screen, so the focused element is always visible when the keyboard is open. The following image below shows ten Input forms and the last one is blue." }, { "code": null, "e": 81449, "s": 81356, "text": "When we tap the blue form, Ionic will adjust our screen, so the blue form is always visible." }, { "code": null, "e": 81722, "s": 81449, "text": "Note − This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates, you will notice that all templates use ion-content directive as a container to other screen elements, so the Scroll View is always applied." }, { "code": null, "e": 81913, "s": 81722, "text": "We already discussed Ionic CSS list elements in the previous chapters. In this chapter, we will show you JavaScript lists. They allow us to use some new features like swipe, drag and remove." }, { "code": null, "e": 82006, "s": 81913, "text": "The directives used for displaying lists and items are ion-list and ion-item as shown below." }, { "code": null, "e": 82163, "s": 82006, "text": "<ion-list>\n <ion-item>\n Item 1 \n </ion-item>\n\t\n <ion-item>\n Item 2 \n </ion-item>\n\t\n <ion-item>\n Item 3 \n </ion-item>\n</ion-list>" }, { "code": null, "e": 82214, "s": 82163, "text": "The above code will produce the following screen −" }, { "code": null, "e": 82533, "s": 82214, "text": "This button can be added by using the ion-delete-button directive. You can use any icon class you want. Since we do not always want to show the delete buttons, because users might accidentally tap it and trigger the delete process, we can add the show-delete attribute to the ion-list and connect it with the ng-model." }, { "code": null, "e": 82671, "s": 82533, "text": "In the following example, we will use the ion-toggle as a model. When the toggle is on delete, the buttons will appear on our list items." }, { "code": null, "e": 83026, "s": 82671, "text": "<ion-list show-delete = \"showDelete1\">\n <ion-item>\n <ion-delete-button class = \"ion-minus-circled\"></ion-delete-button>\n Item 1\n </ion-item>\n\t\n <ion-item>\n <ion-delete-button class = \"ion-minus-circled\"></ion-delete-button>\n Item 2\n </ion-item>\n</ion-list>\n\n<ion-toggle ng-model = \"showDelete2\">\n Show Delete 2\n</ion-toggle>" }, { "code": null, "e": 83077, "s": 83026, "text": "The above code will produce the following screen −" }, { "code": null, "e": 83289, "s": 83077, "text": "The Ionic directive for the reorder button is ion-reorder-button. The element we created has an on-reorder attribute that will trigger the function from our controller whenever the user is dragging this element." }, { "code": null, "e": 83753, "s": 83289, "text": "<ion-list show-reorder = \"true\">\n <ion-item ng-repeat = \"item in items\">\n Item {{item.id}}\n <ion-reorder-button class = \"ion-navicon\" \n on-reorder = \"moveItem(item, $fromIndex, $toIndex)\"></ion-reorder-button>\n </ion-item>\n</ion-list>\n\n$scope.items = [\n {id: 1},\n {id: 2},\n {id: 3},\n {id: 4}\n];\n\n$scope.moveItem = function(item, fromIndex, toIndex) {\n $scope.items.splice(fromIndex, 1);\n $scope.items.splice(toIndex, 0, item);\n};" }, { "code": null, "e": 83804, "s": 83753, "text": "The above code will produce the following screen −" }, { "code": null, "e": 83910, "s": 83804, "text": "When we click the icon on the right, we can drag the element and move it to some other place in the list." }, { "code": null, "e": 84110, "s": 83910, "text": "The Option button is created using an ion-option-button directive. These buttons are showed when the list item is swiped to the left and we can hide it again by swiping the item element to the right." }, { "code": null, "e": 84193, "s": 84110, "text": "You can see in the following example that there are two buttons, which are hidden." }, { "code": null, "e": 84437, "s": 84193, "text": "<ion-list>\n <ion-item>\n Item with two buttons...\n <ion-option-button class = \"button-positive\">Button 1</ion-option-button>\n <ion-option-button class = \"button-assertive\">Button 2</ion-option-button>\n </ion-item>\n</ion-list>" }, { "code": null, "e": 84488, "s": 84437, "text": "The above code will produce the following screen −" }, { "code": null, "e": 84603, "s": 84488, "text": "When we swipe the item element to the left, the text will be moved left and buttons will appear on the right side." }, { "code": null, "e": 84991, "s": 84603, "text": "The collection-repeat function is an updated version of the AngularJS ng-repeat directive. It will only render visible elements on the screen and the rest will be updated as you scroll. This is an important performance improvement when you are working with large lists. This directive can be combined with item-width and item-height attributes for further optimization of the list items." }, { "code": null, "e": 85392, "s": 84991, "text": "There are some other useful attributes for working with images inside your list. The item-render-buffer function represents number of items that are loaded after visible items. The higher this value, the more items will be preloaded. The force-refresh-images function will fix an issue with source of the images while scrolling. Both of these classes will influence the performance in a negative way." }, { "code": null, "e": 85497, "s": 85392, "text": "Ionic loading will disable any interaction with users when showed and enable it again when it is needed." }, { "code": null, "e": 85756, "s": 85497, "text": "Loading is triggered inside the controller. First, we need to inject $ionicLoading in our controller as dependency. After that, we need to call the $ionicLoading.show() method and loading will appear. For disabling it, there is a $ionicLoading.hide() method." }, { "code": null, "e": 85999, "s": 85756, "text": ".controller('myCtrl', function($scope, $ionicLoading) {\n $scope.showLoading = function() {\n $ionicLoading.show({\n template: 'Loading...'\n });\n };\n\n $scope.hideLoading = function(){\n $ionicLoading.hide();\n };\n});" }, { "code": null, "e": 86075, "s": 85999, "text": "<button class = \"button button-block\" ng-click = \"showLoading()\"></button>\n" }, { "code": null, "e": 86227, "s": 86075, "text": "When a user taps the button, the loading will appear. You will usually want to hide the loading after some time consuming functionalities are finished." }, { "code": null, "e": 86340, "s": 86227, "text": "Some other option parameters can be used when working with loading. The explanation is shown in the table below." }, { "code": null, "e": 86459, "s": 86340, "text": "Ionic config is used to configure options you want to be used in all of the $ionicLoading services throughout the app." }, { "code": null, "e": 86632, "s": 86459, "text": "This can be done by using $ionicLoadingConfig. Since constants should be added to the main app module, open your app.js file and add your constant after module declaration." }, { "code": null, "e": 86713, "s": 86632, "text": ".constant('$ionicLoadingConfig', {\n template: 'Default Loading Template...'\n})" }, { "code": null, "e": 86764, "s": 86713, "text": "The above code will produce the following screen −" }, { "code": null, "e": 86998, "s": 86764, "text": "When Ionic modal is activated, the content pane will appear on top of the regular content. Modal is basically larger popup with more functionalities. Modal will cover entire screen by default but it can be optimized the way you want." }, { "code": null, "e": 87365, "s": 86998, "text": "There are a two ways of implementing modal in Ionic. One way is to add separate template and the other is to add it on top of the regular HTML file, inside the script tags. The first thing we need to do is to connect our modal to our controller using angular dependency injection. Then we need to create a modal. We will pass in scope and add animation to our modal." }, { "code": null, "e": 87685, "s": 87365, "text": "After that, we will create functions for opening, closing, destroying modal. The last two functions are placed where we can write the code that will be triggered if a modal is hidden or removed. If you do not want to trigger any functionality, when the modal is removed or hidden, you can delete the last two functions." }, { "code": null, "e": 88406, "s": 87685, "text": ".controller('MyController', function($scope, $ionicModal) {\n $ionicModal.fromTemplateUrl('my-modal.html', {\n scope: $scope,\n animation: 'slide-in-up'\n }).then(function(modal) {\n $scope.modal = modal;\n });\n\t\n $scope.openModal = function() {\n $scope.modal.show();\n };\n\t\n $scope.closeModal = function() {\n $scope.modal.hide();\n };\n\t\n //Cleanup the modal when we're done with it!\n $scope.$on('$destroy', function() {\n $scope.modal.remove();\n });\n\t\n // Execute action on hide modal\n $scope.$on('modal.hidden', function() {\n // Execute action\n });\n\t\n // Execute action on remove modal\n $scope.$on('modal.removed', function() {\n // Execute action\n });\n});" }, { "code": null, "e": 88780, "s": 88406, "text": "<script id = \"my-modal.html\" type = \"text/ng-template\">\n <ion-modal-view>\n <ion-header-bar>\n <h1 class = \"title\">Modal Title</h1>\n </ion-header-bar>\n\t\t\n <ion-content>\n <button class = \"button icon icon-left ion-ios-close-outline\"\n ng-click = \"closeModal()\">Close Modal</button>\n </ion-content>\n </ion-modal-view>\n</script>" }, { "code": null, "e": 88909, "s": 88780, "text": "The way we showed in the last example is when the script tag is used as a container to our modal inside some existing HTML file." }, { "code": null, "e": 89172, "s": 88909, "text": "The second way is to create a new template file inside the templates folder. We will use the same code as in our last example, but we will remove the script tags and we also need to change fromTemplateUrl in controller to connect modal with new created template." }, { "code": null, "e": 89910, "s": 89172, "text": ".controller('MyController', function($scope, $ionicModal) {\n $ionicModal.fromTemplateUrl('templates/modal-template.html', {\n scope: $scope,\n animation: 'slide-in-up',\n }).then(function(modal) {\n $scope.modal = modal;\n });\n\t\n $scope.openModal = function() {\n $scope.modal.show();\n };\n\t\n $scope.closeModal = function() {\n $scope.modal.hide();\n };\n\t\n //Cleanup the modal when we're done with it!\n $scope.$on('$destroy', function() {\n $scope.modal.remove();\n });\n\t\n // Execute action on hide modal\n $scope.$on('modal.hidden', function() {\n // Execute action\n });\n\t\n // Execute action on remove modal\n $scope.$on('modal.removed', function() {\n // Execute action\n });\n});" }, { "code": null, "e": 90190, "s": 89910, "text": "<ion-modal-view>\n <ion-header-bar>\n <h1 class = \"title\">Modal Title</h1>\n </ion-header-bar>\n\t\n <ion-content>\n <button class = \"button icon icon-left ion-ios-close-outline\"\n ng-click = \"closeModal()\">Close Modal</button>\n </ion-content>\n</ion-modal-view>" }, { "code": null, "e": 90324, "s": 90190, "text": "The third way of using Ionic modal is by inserting HTML inline. We will use the fromTemplate function instead of the fromTemplateUrl." }, { "code": null, "e": 91321, "s": 90324, "text": ".controller('MyController', function($scope, $ionicModal) {\n $scope.modal = $ionicModal.fromTemplate( '<ion-modal-view>' +\n ' <ion-header-bar>' +\n '<h1 class = \"title\">Modal Title</h1>' +\n '</ion-header-bar>' +\n\t\t\n '<ion-content>'+\n '<button class = \"button icon icon-left ion-ios-close-outline\"\n ng-click = \"closeModal()\">Close Modal</button>' +\n '</ion-content>' +\n\t\t\n '</ion-modal-view>', {\n scope: $scope,\n animation: 'slide-in-up'\n })\n\n $scope.openModal = function() {\n $scope.modal.show();\n };\n\t\n $scope.closeModal = function() {\n $scope.modal.hide();\n };\n\t\n //Cleanup the modal when we're done with it!\n $scope.$on('$destroy', function() {\n $scope.modal.remove();\n });\n\t\n // Execute action on hide modal\n $scope.$on('modal.hidden', function() {\n // Execute action\n });\n\t\n // Execute action on remove modal\n $scope.$on('modal.removed', function() {\n // Execute action\n });\n});" }, { "code": null, "e": 91440, "s": 91321, "text": "All three examples will have the same effect. We will create a button to trigger the $ionicModal.show() to open modal." }, { "code": null, "e": 91501, "s": 91440, "text": "<button class = \"button\" ng-click = \"openModal()\"></button>\n" }, { "code": null, "e": 91623, "s": 91501, "text": "When we open modal, it will contain a button that will be used for closing it. We created this button in a HTML template." }, { "code": null, "e": 91767, "s": 91623, "text": "There are also other options for modal optimization. We already showed how to use scope and animation. The following table shows other options." }, { "code": null, "e": 91890, "s": 91767, "text": "Navigation is one of the core components of every app. Ionic is using the AngularJS UI Router for handling the navigation." }, { "code": null, "e": 92141, "s": 91890, "text": "Navigation can be configured in the app.js file. If you are using one of the Ionic templates, you will notice the $stateProvider service injected into the app config. The simplest way of creating states for the app is showed in the following example." }, { "code": null, "e": 92267, "s": 92141, "text": "The $stateProvider service will scan the URL, find the corresponding state and load the file, which we defined in app.config." }, { "code": null, "e": 92546, "s": 92267, "text": ".config(function($stateProvider) {\n $stateProvider\n .state('index', { url: '/', templateUrl: 'templates/home.html'})\n .state('state1', {url: '/state1', templateUrl: 'templates/state1.html'})\n .state('state2', {url: '/state2', templateUrl: 'templates/state2.html',});\n});" }, { "code": null, "e": 92646, "s": 92546, "text": "The state will be loaded into the ion-nav-view element, which can be placed in the index.html body." }, { "code": null, "e": 92676, "s": 92646, "text": "<ion-nav-view></ion-nav-view>" }, { "code": null, "e": 92973, "s": 92676, "text": "When we created states in the above-mentioned example, we were using the templateUrl, so when the state is loaded, it will search for matching the template file. Now, we will open the templates folder and create a new file state1.html, which will be loaded when the app URL is changed to /state1." }, { "code": null, "e": 92990, "s": 92973, "text": "state1.html Code" }, { "code": null, "e": 93074, "s": 92990, "text": "<ion-view>\n <ion-content>\n This is State 1 !!!\n </ion-content>\n</ion-view>" }, { "code": null, "e": 93645, "s": 93074, "text": "You can add a navigation bar to your app in the index.html body by adding the “ion-nav-bar” element. Inside the navigation bar, we will add the ion-nav-back-button with an icon. This will be used for returning to the previous state. The button will appear automatically when the state is changed. We will assign the goBack() function, which will use the $ionicHistory service for handling this functionality. Therefore, when the user leaves the home state and goes to state1, the back button will appear which can be taped, if the user wants to return to the home state." }, { "code": null, "e": 93844, "s": 93645, "text": "<ion-nav-bar class = \"bar-positive\">\n <ion-nav-back-button class = \"button-clear\" ng-click = \"goBack()\">\n <i class = \"icon ion-arrow-left-c\"></i> Back\n </ion-nav-back-button>\n</ion-nav-bar>" }, { "code": null, "e": 93949, "s": 93844, "text": ".MyCtrl($scope, $ionicHistory) {\n $scope.goBack = function() {\n $ionicHistory.goBack();\n };\n} " }, { "code": null, "e": 94392, "s": 93949, "text": "Buttons can be added to the navigation bar using the ion-nav-buttons. This element should be placed inside the ion-nav-bar or the ion-view. We can assign the side attribute with four option values. The primary and secondary values will place buttons according to the platform that is used. Sometimes you want the buttons on one side no matter if it is IOS or Android. If that is the case, you can use the left or the right attributes instead." }, { "code": null, "e": 94531, "s": 94392, "text": "We can also add the ion-nav-title to the navigation bar. All the code will be placed in the index.html body, so it can be used everywhere." }, { "code": null, "e": 94762, "s": 94531, "text": "<ion-nav-bar class = \"bar-positive\">\n <ion-nav-title>\n Title\n </ion-nav-title>\n\t\n <ion-nav-buttons side = \"primary\">\n <button class = \"button\">\n Button 1\n </button>\n </ion-nav-buttons>\n</ion-nav-bar>" }, { "code": null, "e": 94801, "s": 94762, "text": "It will produce the following screen −" }, { "code": null, "e": 94897, "s": 94801, "text": "The following table shows a few other functionalities, which can be used with Ionic navigation." }, { "code": null, "e": 95192, "s": 94897, "text": "Ionic has the ability for caching up to ten views to improve performance. It also offers a way to handle caching manually. Since only backward views are cached and the forward ones are loading each time the users visit them, we can easily set to cache forward views by using following the code." }, { "code": null, "e": 95240, "s": 95192, "text": "$ionicCinfigProvider.views.forwardCache(true);\n" }, { "code": null, "e": 95358, "s": 95240, "text": "We can also set how many states should be cached. If we want three views to be cached, we can use the following code." }, { "code": null, "e": 95399, "s": 95358, "text": "$ionicConfigProvider.views.maxCache(3);\n" }, { "code": null, "e": 95507, "s": 95399, "text": "Caching can be disabled inside $stateProvider or by setting attribute to ion-view. Both examples are below." }, { "code": null, "e": 95664, "s": 95507, "text": "$stateProvider.state('state1', {\n cache: false,\n url : '/state1',\n templateUrl: 'templates/state1.html'\n})\n\n<ion-view cache-view = \"false\"></ion-view>" }, { "code": null, "e": 95810, "s": 95664, "text": "We can control the behavior of the navigation bar by using the $ionicNavBarDelegate service. This service needs to be injected to our controller." }, { "code": null, "e": 95925, "s": 95810, "text": "<ion-nav-bar>\n <button ng-click = \"setNavTitle('title')\">\n Set title to banana!\n </button>\n</ion-nav-bar>" }, { "code": null, "e": 96004, "s": 95925, "text": "$scope.setNavTitle = function(title) {\n $ionicNavBarDelegate.title(title);\n}" }, { "code": null, "e": 96120, "s": 96004, "text": "The $ionicNavBarDelegate service has other useful methods. Some of these methods are listed in the following table." }, { "code": null, "e": 96288, "s": 96120, "text": "You can track the history of the previous, current and the forward views by using the $ionicHistory service. The following table shows all the methods of this service." }, { "code": null, "e": 96360, "s": 96288, "text": "The nextViewOptions() method has the following three options available." }, { "code": null, "e": 96432, "s": 96360, "text": "disableAnimate is used for disabling animation of the next view change." }, { "code": null, "e": 96504, "s": 96432, "text": "disableAnimate is used for disabling animation of the next view change." }, { "code": null, "e": 96548, "s": 96504, "text": "disableBack will set the back view to null." }, { "code": null, "e": 96592, "s": 96548, "text": "disableBack will set the back view to null." }, { "code": null, "e": 96645, "s": 96592, "text": "historyRoot will set the next view as the root view." }, { "code": null, "e": 96698, "s": 96645, "text": "historyRoot will set the next view as the root view." }, { "code": null, "e": 96780, "s": 96698, "text": "$ionicHistory.nextViewOptions({\n disableAnimate: true,\n disableBack: true\n});" }, { "code": null, "e": 96836, "s": 96780, "text": "This is a view that will appear above the regular view." }, { "code": null, "e": 97018, "s": 96836, "text": "A Popover can be created by using ion-popover-view element. This element should be added to the HTML template and the $ionicPopover service needs to be injected into the controller." }, { "code": null, "e": 97225, "s": 97018, "text": "There are three ways of adding popover. The first one is the fromTemplate method, which allows using the inline template. The second and the third way of adding popover is to use the fromTemplateUrl method." }, { "code": null, "e": 97287, "s": 97225, "text": "Let us understand the fromtemplate method as explained below." }, { "code": null, "e": 98222, "s": 97287, "text": ".controller('DashCtrl', function($scope, $ionicLoading, $ionicPopover) {\n // .fromTemplate() method\n var template = '<ion-popover-view>' + '<ion-header-bar>' +\n '<h1 class = \"title\">Popover Title</h1>' +\n '</ion-header-bar>'+ '<ion-content>' +\n 'Popover Content!' + '</ion-content>' + '</ion-popover-view>';\n\n $scope.popover = $ionicPopover.fromTemplate(template, {\n scope: $scope\n });\n\n $scope.openPopover = function($event) {\n $scope.popover.show($event);\n };\n\n $scope.closePopover = function() {\n $scope.popover.hide();\n };\n\n //Cleanup the popover when we're done with it!\n $scope.$on('$destroy', function() {\n $scope.popover.remove();\n });\n\n // Execute action on hide popover\n $scope.$on('popover.hidden', function() {\n // Execute action\n });\n\n // Execute action on remove popover\n $scope.$on('popover.removed', function() {\n // Execute action\n });\n})" }, { "code": null, "e": 98408, "s": 98222, "text": "As discussed above, the second and the third way of adding popover is to use fromTemplateUrl method. The controller code will be the same for both ways except the fromTemplateUrl value." }, { "code": null, "e": 98596, "s": 98408, "text": "If the HTML is added to an existing template, the URL will be the popover.html. If we want to place the HTML into the templates folder, then the URL will change to templates/popover.html." }, { "code": null, "e": 98637, "s": 98596, "text": "Both examples have been explained below." }, { "code": null, "e": 99356, "s": 98637, "text": ".controller('MyCtrl', function($scope, $ionicPopover) {\n\n $ionicPopover.fromTemplateUrl('popover.html', {\n scope: $scope\n }).then(function(popover) {\n $scope.popover = popover;\n });\n\n $scope.openPopover = function($event) {\n $scope.popover.show($event);\n };\n\n $scope.closePopover = function() {\n $scope.popover.hide();\n };\n\n //Cleanup the popover when we're done with it!\n $scope.$on('$destroy', function() {\n $scope.popover.remove();\n });\n\n // Execute action on hide popover\n $scope.$on('popover.hidden', function() {\n // Execute action\n });\n\n // Execute action on remove popover\n $scope.$on('popover.removed', function() {\n // Execute action\n });\n})" }, { "code": null, "e": 99469, "s": 99356, "text": "Now, we will add the script with template to the HTML file, which we are using for calling the popover function." }, { "code": null, "e": 99749, "s": 99469, "text": "<script id = \"popover.html\" type = \"text/ng-template\">\n <ion-popover-view>\n\t\n <ion-header-bar>\n <h1 class = \"title\">Popover Title</h1>\n </ion-header-bar>\n\t\t\n <ion-content>\n Popover Content!\n </ion-content>\n\t\t\n </ion-popover-view>\n</script>" }, { "code": null, "e": 99941, "s": 99749, "text": "If we want to create an HTML as a separate file, we can create a new HTML file in the templates folder and use the same code as we used in the above-mentioned example without the script tags." }, { "code": null, "e": 99984, "s": 99941, "text": "The newly created HTML file is as follows." }, { "code": null, "e": 100169, "s": 99984, "text": "<ion-popover-view>\n <ion-header-bar>\n <h1 class = \"title\">Popover Title</h1>\n </ion-header-bar>\n\t\n <ion-content>\n Popover Content!\n </ion-content>\n</ion-popover-view>" }, { "code": null, "e": 100256, "s": 100169, "text": "The last thing we need is to create a button that will be clicked to show the popover." }, { "code": null, "e": 100336, "s": 100256, "text": "<button class = \"button\" ng-click = \"openPopover($event)\">Add Popover</button>\n" }, { "code": null, "e": 100416, "s": 100336, "text": "Whatever way we choose from above examples, the output will always be the same." }, { "code": null, "e": 100486, "s": 100416, "text": "The following table shows the $ionicPopover methods that can be used." }, { "code": null, "e": 100687, "s": 100486, "text": "This service is used for creating a popup window on top of the regular view, which will be used for interaction with the users. There are four types of popups namely − show, confirm, alert and prompt." }, { "code": null, "e": 101121, "s": 100687, "text": "This popup is the most complex of all. To trigger popups, we need to inject the $ionicPopup service to our controller and then just add a method that will trigger the popup we want to use, in this case $ionicPopup.show(). The onTap(e) function can be used for adding e.preventDefault() method, which will keep the popup open, if there is no change applied to the input. When the popup is closed, the promised object will be resolved." }, { "code": null, "e": 102088, "s": 101121, "text": ".controller('MyCtrl', function($scope, $ionicPopup) {\n // When button is clicked, the popup will be shown...\n $scope.showPopup = function() {\n $scope.data = {}\n \n // Custom popup\n var myPopup = $ionicPopup.show({\n template: '<input type = \"text\" ng-model = \"data.model\">',\n title: 'Title',\n subTitle: 'Subtitle',\n scope: $scope,\n\t\t\t\n buttons: [\n { text: 'Cancel' }, {\n text: '<b>Save</b>',\n type: 'button-positive',\n onTap: function(e) {\n\t\t\t\t\t\t\n if (!$scope.data.model) {\n //don't allow the user to close unless he enters model...\n e.preventDefault();\n } else {\n return $scope.data.model;\n }\n }\n }\n ]\n });\n\n myPopup.then(function(res) {\n console.log('Tapped!', res);\n }); \n };\n})" }, { "code": null, "e": 102163, "s": 102088, "text": "<button class = \"button\" ng-click = \"showPopup()\">Add Popup Show</button>\n" }, { "code": null, "e": 102317, "s": 102163, "text": "You probably noticed in the above-mentioned example some new options were used. The following table will explain all of those options and their use case." }, { "code": null, "e": 102556, "s": 102317, "text": "A Confirm Popup is the simpler version of Ionic popup. It contains Cancel and OK buttons that users can press to trigger the corresponding functionality. It returns the promised object that is resolved when one of the buttons are pressed." }, { "code": null, "e": 102997, "s": 102556, "text": ".controller('MyCtrl', function($scope, $ionicPopup) {\n // When button is clicked, the popup will be shown...\n $scope.showConfirm = function() {\n\t var confirmPopup = $ionicPopup.confirm({\n title: 'Title',\n template: 'Are you sure?'\n });\n\n confirmPopup.then(function(res) {\n if(res) {\n console.log('Sure!');\n } else {\n console.log('Not sure!');\n }\n });\n\t};\n})" }, { "code": null, "e": 103077, "s": 102997, "text": "<button class = \"button\" ng-click = \"showConfirm()\">Add Popup Confirm</button>\n" }, { "code": null, "e": 103151, "s": 103077, "text": "The following table explains the options that can be used for this popup." }, { "code": null, "e": 103337, "s": 103151, "text": "An Alert is a simple popup that is used for displaying the alert information to the user. It has only one button that is used to close the popup and resolve the popups’ promised object." }, { "code": null, "e": 103634, "s": 103337, "text": ".controller('MyCtrl', function($scope, $ionicPopup) {\n $scope.showAlert = function() {\n var alertPopup = $ionicPopup.alert({\n title: 'Title',\n template: 'Alert message'\n });\n\n alertPopup.then(function(res) {\n // Custom functionality....\n });\n };\n})" }, { "code": null, "e": 103710, "s": 103634, "text": "<button class = \"button\" ng-click = \"showAlert()\">Add Popup Alert</button>\n" }, { "code": null, "e": 103749, "s": 103710, "text": "It will produce the following screen −" }, { "code": null, "e": 103824, "s": 103749, "text": "The following table shows the options that can be used for an alert popup." }, { "code": null, "e": 104010, "s": 103824, "text": "The last Ionic popup that can be created using Ionic is prompt. It has an OK button that resolves promise with value from the input and Cancel button that resolves with undefined value." }, { "code": null, "e": 104379, "s": 104010, "text": ".controller('MyCtrl', function($scope, $ionicPopup) {\n $scope.showPrompt = function() {\n var promptPopup = $ionicPopup.prompt({\n title: 'Title',\n template: 'Template text',\n inputType: 'text',\n inputPlaceholder: 'Placeholder'\n });\n \n promptPopup.then(function(res) {\n console.log(res);\n });\n };\n})" }, { "code": null, "e": 104457, "s": 104379, "text": "<button class = \"button\" ng-click = \"showPrompt()\">Add Popup Prompt</button>\n" }, { "code": null, "e": 104496, "s": 104457, "text": "It will produce the following screen −" }, { "code": null, "e": 104567, "s": 104496, "text": "The following table shows options that can be used for a prompt popup." }, { "code": null, "e": 104654, "s": 104567, "text": "The element used for scrolling manipulation in ionic apps is called as the ion-scroll." }, { "code": null, "e": 104943, "s": 104654, "text": "The following code snippets will create scrollable containers and adjust scrolling patterns. First, we will create our HTML element and add properties to it. We will add → direction = \"xy\" to allow scrolling to every side. We will also set the width and the height for the scroll element." }, { "code": null, "e": 105084, "s": 104943, "text": "<ion-scroll zooming = \"true\" direction = \"xy\" style = \"width: 320px; height: 500px\">\n <div class = \"scroll-container\"></div>\n</ion-scroll>" }, { "code": null, "e": 105214, "s": 105084, "text": "Next, we will add the image of our world map to div element, which we created inside the ion-scroll and set its width and height." }, { "code": null, "e": 105326, "s": 105214, "text": ".scroll-container {\n width: 2600px;\n height: 1000px;\n background: url('../img/world-map.png') no-repeat\n}" }, { "code": null, "e": 105452, "s": 105326, "text": "When we run our app, we can scroll the map in every direction. The following example shows the North America part of the map." }, { "code": null, "e": 105532, "s": 105452, "text": "We can scroll this map to any part that we want. Let us scroll it to show Asia." }, { "code": null, "e": 105643, "s": 105532, "text": "There are other attributes, which can be applied to the ion-scroll. You can check them in the following table." }, { "code": null, "e": 106083, "s": 105643, "text": "An Infinite scroll is used to trigger some behavior when scrolling passes the bottom of the page. The following example shows how this works. In our controller, we created a function for adding items to the list. These items will be added when a scroll passes 10% of the last element loaded. This will continue until we hit 30 loaded elements. Every time loading is finished, on-infinite will broadcast scroll.infiniteScrollComplete event." }, { "code": null, "e": 106316, "s": 106083, "text": "<ion-list>\n <ion-item ng-repeat = \"item in items\" item = \"item\">Item {{ item.id }}</ion-item>\n</ion-list>\n\n<ion-infinite-scroll ng-if = \"!noMoreItemsAvailable\" on-infinite = \"loadMore()\" \n distance = \"10%\"></ion-infinite-scroll>" }, { "code": null, "e": 106675, "s": 106316, "text": ".controller('MyCtrl', function($scope) {\n $scope.items = [];\n $scope.noMoreItemsAvailable = false;\n \n $scope.loadMore = function() {\n $scope.items.push({ id: $scope.items.length}); \n\n if ($scope.items.length == 30) {\n $scope.noMoreItemsAvailable = true;\n }\n \n $scope.$broadcast('scroll.infiniteScrollComplete');\n };\n})" }, { "code": null, "e": 106779, "s": 106675, "text": "Other attributes can also be used with ion-infinite-scroll. Some of them are listed in the table below." }, { "code": null, "e": 106958, "s": 106779, "text": "Ionic offers delegate for full control of the scroll elements. It can be used by injecting a $ionicScrollDelegate service to the controller, and then use the methods it provides." }, { "code": null, "e": 107019, "s": 106958, "text": "The following example shows a scrollable list of 20 objects." }, { "code": null, "e": 107853, "s": 107019, "text": "<div class = \"list\">\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n <div class = \"item\">Item 4</div>\n <div class = \"item\">Item 5</div>\n <div class = \"item\">Item 6</div>\n <div class = \"item\">Item 7</div>\n <div class = \"item\">Item 8</div>\n <div class = \"item\">Item 9</div>\n <div class = \"item\">Item 10</div>\n <div class = \"item\">Item 11</div>\n <div class = \"item\">Item 12</div>\n <div class = \"item\">Item 13</div>\n <div class = \"item\">Item 14</div>\n <div class = \"item\">Item 15</div>\n <div class = \"item\">Item 16</div>\n <div class = \"item\">Item 17</div>\n <div class = \"item\">Item 18</div>\n <div class = \"item\">Item 19</div>\n <div class = \"item\">Item 20</div>\n</div>\n\n<button class = \"button\" ng-click = \"scrollTop()\">Scroll to Top!</button>" }, { "code": null, "e": 108006, "s": 107853, "text": ".controller('DashCtrl', function($scope, $ionicScrollDelegate) {\n\n $scope.scrollTop = function() {\n $ionicScrollDelegate.scrollTop();\n };\n}) " }, { "code": null, "e": 108057, "s": 108006, "text": "The above code will produce the following screen −" }, { "code": null, "e": 108118, "s": 108057, "text": "When we tap the button, the scroll will be moved to the top." }, { "code": null, "e": 108183, "s": 108118, "text": "Now, we will go through all of the $ionicScrollDelegate methods." }, { "code": null, "e": 108349, "s": 108183, "text": "Side menu is one of the most used Ionic components. The Side menu can be opened by swiping to the left or right or by triggering the button created for that purpose." }, { "code": null, "e": 108795, "s": 108349, "text": "The first element that we need is ion-side-menus. This element is used for connecting the side menu with all the screens that will use it. The ion-side-menu-content element is where the content will be placed and the ion-side-menu element is the place where we can put a side directive. We will add the side menu to the index.html and place the ion-nav-view inside the side menu content. This way the side menu can be used throughout entire app." }, { "code": null, "e": 109009, "s": 108795, "text": "<ion-side-menus>\n\n <ion-side-menu>side = \"left\">\n <h1>SIde Menu</h1>\n </ion-side-menu>\n\n <ion-side-menu-content>\n <ion-nav-view>\n </ion-nav-view>\n </ion-side-menu-content>\n\n</ion-side-menus>" }, { "code": null, "e": 109198, "s": 109009, "text": "Now, we will create button with menu-toggle = \"left\" directive. This button will usually be placed in the apps header bar, but we will add it in our template file for better understanding." }, { "code": null, "e": 109434, "s": 109198, "text": "When the button is tapped or when we swipe to the right, the side menu will open. You could also set the menu-close directive, if you would like to have one button only for closing side menu, but we will use the toggle button for this." }, { "code": null, "e": 109520, "s": 109434, "text": "<button menu-toggle = \"left\" class = \"button button-icon icon ion-navicon\"></button>\n" }, { "code": null, "e": 109571, "s": 109520, "text": "The above code will produce the following screen −" }, { "code": null, "e": 109914, "s": 109571, "text": "You can add some additional attributes to the ion-side-menus element. The enable-menu-with-back-views can be set to false to disable side menu, when the back button is showed. This will also hide the menu-toggle button from the header. The other attribute is delegate-handle, which will be used for the connection with $ionicSideMenuDelegate." }, { "code": null, "e": 110380, "s": 109914, "text": "The ion-side-menu-content element can use its own attribute. When the drag-content attribute is set to false, it will disable the ability to open the side menu by swiping the content screen. The edge-drag-threshold attribute has a default value of 25. This means that swiping is allowed only 25 pixels from the left and right edge of the screen. We can change this number value or we can set it to false to enable swiping on the entire screen or true to disable it." }, { "code": null, "e": 110736, "s": 110380, "text": "The ion-side-menu can use the side attribute that we showed in the example above. It will determine whether the menu should appear from the left or the right side. The ‘is-enabled’ attribute with a false value will disable the side menu, and the width attribute value is a number that represents how wide the side menu should be. The default value is 275." }, { "code": null, "e": 111107, "s": 110736, "text": "The $ionicSideMenuDelegate is a service used for controlling all the side menus in the app. We will show you how to use it, and then we will go through all the options available. Like all the Ionic services, we need to add it as a dependency to our controller and then use it inside the controller’s scope. Now, when we click the button, all of the side menus will open." }, { "code": null, "e": 111268, "s": 111107, "text": ".controller('MyCtrl', function($scope, $ionicSideMenuDelegate) {\n $scope.toggleLeftSideMenu = function() {\n $ionicSideMenuDelegate.toggleLeft();\n };\n})" }, { "code": null, "e": 111359, "s": 111268, "text": "<button class = \"button button-icon icon ion-navicon\" ng-click = \"toggleLeft()\"></button>\n" }, { "code": null, "e": 111419, "s": 111359, "text": "The following table shows the $ionicScrollDelegate methods." }, { "code": null, "e": 111497, "s": 111419, "text": "A Slide box contains pages that can be changed by swiping the content screen." }, { "code": null, "e": 111703, "s": 111497, "text": "The usage of the slide box is simple. You just need to add ion-slide-box as a container and ion-slide with box class inside that container. We will add height and border to our boxes for better visibility." }, { "code": null, "e": 112105, "s": 111703, "text": "<ion-slide-box>\n\n <ion-slide>\n <div class = \"box box1\">\n <h1>Box 1</h1>\n </div>\n </ion-slide>\n\n <ion-slide>\n <div class = \"box box2\">\n <h1>Box 2</h1>\n </div>\n </ion-slide>\n\n <ion-slide>\n <div class = \"box box3\">\n <h1>Box 3</h1>\n </div>\n </ion-slide>\n\n</ion-slide-box>\n\n.box1, box2, box3 {\n height: 300px;\n border: 2px solid blue;\n}" }, { "code": null, "e": 112165, "s": 112105, "text": "The Output will look as shown in the following screenshot −" }, { "code": null, "e": 112280, "s": 112165, "text": "We can change the box by dragging the content to the right. We can also drag to the left to show the previous box." }, { "code": null, "e": 112387, "s": 112280, "text": "A few attributes that can be used for controlling slide box behavior are mentioned in the following table." }, { "code": null, "e": 112505, "s": 112387, "text": "The $ionicSlideBoxDelegate is a service used for controlling all slide boxes. We need to inject it to the controller." }, { "code": null, "e": 112650, "s": 112505, "text": ".controller('MyCtrl', function($scope, $ionicSlideBoxDelegate) {\n $scope.nextSlide = function() {\n $ionicSlideBoxDelegate.next();\n }\n})" }, { "code": null, "e": 112740, "s": 112650, "text": "<button class = \"button button-icon icon ion-navicon\" ng-click = \"nextSlide()\"></button>\n" }, { "code": null, "e": 112798, "s": 112740, "text": "The following table shows $ionicSlideBoxDelegate methods." }, { "code": null, "e": 113000, "s": 112798, "text": "Tabs are a useful pattern for any navigation type or selecting different pages inside your app. The same tabs will appear at the top of the screen for Android devices and at the bottom for IOS devices." }, { "code": null, "e": 113281, "s": 113000, "text": "Tabs can be added to the app by using ion-tabs as a container element and ion-tab as a content element. We will add it to the index.html, but you can add it to any HTML file inside your app. Just be sure not to add it inside the ion-content to avoid CSS issues that comes with it." }, { "code": null, "e": 113654, "s": 113281, "text": "<ion-tabs class = \"tabs-icon-only\">\n\n <ion-tab title = \"Home\" icon-on = \"ion-ios-filing\" \n icon-off = \"ion-ios-filing-outline\"></ion-tab>\n\n <ion-tab title = \"About\" icon-on = \"ion-ios-home\" \n icon-off = \"ion-ios-home-outline\"></ion-tab>\n\n <ion-tab title = \"Settings\" icon-on = \"ion-ios-star\" \n icon-off = \"ion-ios-star-outline\"></ion-tab>\n\n</ion-tabs>" }, { "code": null, "e": 113713, "s": 113654, "text": "The output will look as shown in the following screenshot." }, { "code": null, "e": 114067, "s": 113713, "text": "There is API available for ion-tab elements. You can add it as attributes as showed in example above where we used title, icon-on and icon-off. The last two are used to differentiate selected tab from the rest of it. If you look at the image above, you can see that first tab is selected. You can check the rest of the attributes in the following table." }, { "code": null, "e": 114260, "s": 114067, "text": "Tabs also have its own delegate service for easier control of all the tabs inside the app. It can be injected in the controller and has several methods, which are shown in the following table." }, { "code": null, "e": 114357, "s": 114260, "text": "Cordova offers ngCordova, which is set of wrappers specifically designed to work with AngularJS." }, { "code": null, "e": 114595, "s": 114357, "text": "When you the start Ionic app, you will notice that it is using bower. It can be used for managing ngCordova plugins. If you have bower installed skip this step, if you do not have it, then you can install it in the command prompt window." }, { "code": null, "e": 114650, "s": 114595, "text": "C:\\Users\\Username\\Desktop\\MyApp> npm install -g bower\n" }, { "code": null, "e": 114821, "s": 114650, "text": "Now we need to install ngCordova. Open your app in the command prompt window. The following example is used for the app that is located on the desktop and is named MyApp." }, { "code": null, "e": 114879, "s": 114821, "text": "C:\\Users\\Username\\Desktop\\MyApp> bower install ngCordova\n" }, { "code": null, "e": 115058, "s": 114879, "text": "Next, we need to include ngCordova to our app. Open index.html file and add the following scripts. It is important to add these scripts before cordova.js and after ionic scripts." }, { "code": null, "e": 115118, "s": 115058, "text": "<script src = \"lib/ngCordova/dist/ng-cordova.js\"></script>\n" }, { "code": null, "e": 115425, "s": 115118, "text": "Now, we need to inject ngCordova as angular dependency. Open your app.js file and add the ngCordova to angular module. If you have used one of the Ionic template apps, you will notice that there is injected ionic, controllers and services. In that case, you will just add ngCordova at the end of the array." }, { "code": null, "e": 115465, "s": 115425, "text": "angular.module('myApp', ['ngCordova'])\n" }, { "code": null, "e": 115559, "s": 115465, "text": "You can always check the plugins that are already installed by typing the following command. " }, { "code": null, "e": 115612, "s": 115559, "text": "C:\\Users\\Username\\Desktop\\MyApp> cordova plugins ls\n" }, { "code": null, "e": 115691, "s": 115612, "text": "Now, we can use the Cordova plugins. You can check all the other plugins here." }, { "code": null, "e": 115834, "s": 115691, "text": "The Cordova AdMob plugin is used for integrating ads natively. We will use the admobpro plugin in this chapter, since the admob is deprecated." }, { "code": null, "e": 116110, "s": 115834, "text": "To be able to use ads in your app, you need to sign up to admob and create a banner. When you do this, you will get an Ad Publisher ID. Since these steps are not a part of the Ionic framework, we will not explain it here. You can follow the steps by Google support team here." }, { "code": null, "e": 116304, "s": 116110, "text": "You will also need to have android or iOS platform installed, since the cordova plugins work only on native platforms. We have already discussed how to do this in our environment setup chapter." }, { "code": null, "e": 116368, "s": 116304, "text": "The AdMob plugin can be installed in the command prompt window." }, { "code": null, "e": 116445, "s": 116368, "text": "C:\\Users\\Username\\Desktop\\MyApp> cordova plugin add cordova-plugin-admobpro\n" }, { "code": null, "e": 116656, "s": 116445, "text": "Now that we have installed the plugin, we need to check if the device is ready before we are able to use it. This is why we need to add the following code in the $ionicPlatform.ready function inside the app.js." }, { "code": null, "e": 116974, "s": 116656, "text": "if( ionic.Platform.isAndroid() ) { \n admobid = { // for Android\n banner: 'ca-app-pub-xxx/xxx' // Change this to your Ad Unit Id for banner...\n };\n\n if(AdMob) \n AdMob.createBanner( {\n adId:admobid.banner, \n position:AdMob.AD_POSITION.BOTTOM_CENTER, \n autoShow:true\n } );\n}" }, { "code": null, "e": 117033, "s": 116974, "text": "The output will look as shown in the following screenshot." }, { "code": null, "e": 117225, "s": 117033, "text": "The same code can be applied for iOS or a Windows Phone. You will only use a different id for these platforms. Instead of a banner, you can use interstitial ads that will cover entire screen." }, { "code": null, "e": 117288, "s": 117225, "text": "The following table shows methods that can be used with admob." }, { "code": null, "e": 117354, "s": 117288, "text": "The following table shows the events that can be used with admob." }, { "code": null, "e": 117414, "s": 117354, "text": "You can handle these events by following the example below." }, { "code": null, "e": 117497, "s": 117414, "text": "document.addEventListener('onAdLoaded', function(e){\n // Handle the event...\n});" }, { "code": null, "e": 117608, "s": 117497, "text": "The Cordova camera plugin uses the native camera for taking pictures or getting images from the image gallery." }, { "code": null, "e": 117737, "s": 117608, "text": "Open your project root folder in command prompt, then download and install the Cordova camera plugin with the following command." }, { "code": null, "e": 117816, "s": 117737, "text": "C:\\Users\\Username\\Desktop\\MyApp> cordova plugin add org.apache.cordova.camera\n" }, { "code": null, "e": 117971, "s": 117816, "text": "Now, we will create a service for using a camera plugin. We will use the AngularJS factory and promise object $q that needs to be injected to the factory." }, { "code": null, "e": 118294, "s": 117971, "text": ".factory('Camera', function($q) {\n return {\n getPicture: function(options) {\n var q = $q.defer();\n\n navigator.camera.getPicture(function(result) {\n q.resolve(result);\n }, function(err) {\n q.reject(err);\n }, options);\n\n return q.promise;\n }\n }\n});" }, { "code": null, "e": 118486, "s": 118294, "text": "To use this service in the app, we need to inject it to a controller as a dependency. Cordova camera API provides the getPicture method, which is used for taking photos using a native camera." }, { "code": null, "e": 118960, "s": 118486, "text": "The native camera settings can be additionally customized by passing the options parameter to the takePicture function. Copy the above-mentioned code sample to your controller to trigger this behavior. It will open the camera application and return a success callback function with the image data or error callback function with an error message. We will also need two buttons that will call the functions we are about to create and we need to show the image on the screen." }, { "code": null, "e": 119141, "s": 118960, "text": "<button class = \"button\" ng-click = \"takePicture()\">Take Picture</button>\n<button class = \"button\" ng-click = \"getPicture()\">Open Gallery</button>\n<img ng-src = \"{{user.picture}}\">" }, { "code": null, "e": 119537, "s": 119141, "text": ".controller('MyCtrl', function($scope, Camera) {\n $scope.takePicture = function (options) {\n var options = {\n quality : 75,\n targetWidth: 200,\n targetHeight: 200,\n sourceType: 1\n };\n\n Camera.getPicture(options).then(function(imageData) {\n $scope.picture = imageData;;\n }, function(err) {\n console.log(err);\n });\n };\n})" }, { "code": null, "e": 119596, "s": 119537, "text": "The output will look as shown in the following screenshot." }, { "code": null, "e": 119844, "s": 119596, "text": "If you want to use images from your gallery, the only thing you need to change is the sourceType method from your options parameter. This change will open a dialog popup instead of camera and allow you to choose the image you want from the device." }, { "code": null, "e": 120002, "s": 119844, "text": "You can see the following code, where the sourceType option is changed to 0. Now, when you tap the second button, it will open the file menu from the device." }, { "code": null, "e": 120397, "s": 120002, "text": ".controller('MyCtrl', function($scope, Camera) {\n $scope.getPicture = function (options) {\n\t var options = {\n quality : 75,\n targetWidth: 200,\n targetHeight: 200,\n sourceType: 0\n };\n\n Camera.getPicture(options).then(function(imageData) {\n $scope.picture = imageData;;\n }, function(err) {\n console.log(err);\n });\n }; \n})" }, { "code": null, "e": 120456, "s": 120397, "text": "The output will look as shown in the following screenshot." }, { "code": null, "e": 120555, "s": 120456, "text": "When you save the image you took, it will appear on the screen. You can style it the way you want." }, { "code": null, "e": 120646, "s": 120555, "text": "Several other options can be used as well, some of which are given in the following table." }, { "code": null, "e": 120984, "s": 120646, "text": "This plugin is used for connecting to Facebook API. Before you start integrating Facebook, you need to create a Facebook app here. You will create a web app and then skip the quick start screen. Then, you need to add the website platform on the settings page. You can use the following code snippet for the site URL while in development." }, { "code": null, "e": 121008, "s": 120984, "text": "http://localhost:8100/\n" }, { "code": null, "e": 121127, "s": 121008, "text": "After that, you need to add Valid OAuth redirect URIs on the settings/advanced page. Just copy the following two URLs." }, { "code": null, "e": 121221, "s": 121127, "text": "https://www.facebook.com/connect/login_success.html\nhttp://localhost:8100/oauthcallback.html\n" }, { "code": null, "e": 121644, "s": 121221, "text": "We did all the steps above to tackle some issues that often appear when using this plugin. This plugin is hard to set up because there are a lot of steps involved and documentation doesn't cover all of them. There are also some known compatibility issues with other Cordova plugins, so we will use Teleric verified plugin version in our app. We will start by installing browser platform to our app from the command prompt." }, { "code": null, "e": 121704, "s": 121644, "text": "C:\\Users\\Username\\Desktop\\MyApp>ionic platform add browser\n" }, { "code": null, "e": 121794, "s": 121704, "text": "Next, what we need to do is to add the root element on top of the body tag in index.html." }, { "code": null, "e": 121822, "s": 121794, "text": "<div id = \"fb-root\"></div>\n" }, { "code": null, "e": 121959, "s": 121822, "text": "Now we will add Cordova Facebook plugin to our app. You need to change APP_ID and APP_NAME to match the Facebook app you created before." }, { "code": null, "e": 122142, "s": 121959, "text": "C:\\Users\\Username\\Desktop\\MyApp>cordova -d plugin add \n https://github.com/Telerik-Verified-Plugins/Facebook/ \n --variable APP_ID = \"123456789\" --variable APP_NAME = \"FbAppName\"\n" }, { "code": null, "e": 122406, "s": 122142, "text": "Now open index.html and add the following code after your body tag. Again you need to make sure that the appId and version are matching the Facebook app you created. This will ensure that Facebook SDK is loaded asynchronously without blocking the rest of the app." }, { "code": null, "e": 122890, "s": 122406, "text": "<script>\n window.fbAsyncInit = function() {\n FB.init({\n appId : '123456789',\n xfbml : true,\n version : 'v2.4'\n });\n };\n\n (function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/en_US/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n</script>" }, { "code": null, "e": 123199, "s": 122890, "text": "Since we installed everything, we need to create service that will be our connection to the Facebook. These things can be done with less code inside the controller, but we try to follow the best practices, so we will use Angular service. The following code shows the entire service. We will explain it later." }, { "code": null, "e": 124437, "s": 123199, "text": ".service('Auth', function($q, $ionicLoading) {\n this.getLoginStatus = function() {\n var defer = $q.defer();\n \n FB.getLoginStatus(function(response) {\n\t\t if (response.status === \"connected\") {\n console.log(JSON.stringify(response));\n } else {\n console.log(\"Not logged in\");\n }\n });\n\n return defer.promise;\n }\n this.loginFacebook = function() {\n var defer = $q.defer();\n\n FB.login(function(response) {\n\t\t if (response.status === \"connected\") {\n console.log(JSON.stringify(response));\n } else {\n console.log(\"Not logged in!\");\n }\n });\n\n return defer.promise;\n }\n this.logoutFacebook = function() {\n var defer = $q.defer();\n\n FB.logout(function(response) {\n console.log('You are logged out!');\n });\n\n return defer.promise;\n }\n this.getFacebookApi = function() {\n var defer = $q.defer();\n\n FB.api(\"me/?fields = id,email\", [], function(response) {\n\t\t\n if (response.error) {\n console.log(JSON.stringify(response.error));\n } else {\n console.log(JSON.stringify(response));\n }\n });\n\n return defer.promise;\n }\n});" }, { "code": null, "e": 124647, "s": 124437, "text": "In the above service, we are creating four functions. First three are self-explanatory. The fourth function is used for connecting to Facebook graph API. It will return the id and email from the Facebook user." }, { "code": null, "e": 124938, "s": 124647, "text": "We are creating promise objects to handle asynchronic JavaScript functions. Now we need to write our controller that will call those functions. We will call each function separately for better understanding, but you will probably need to mix some of them together to get the desired effect." }, { "code": null, "e": 125615, "s": 124938, "text": ".controller('MyCtrl', function($scope, Auth, $ionicLoading) {\n \n $scope.checkLoginStatus = function() {\n getLoginUserStatus();\n }\n\n $scope.loginFacebook = function(userData) {\n loginFacebookUser();\n };\n\n $scope.facebookAPI = function() {\n getFacebookUserApi();\n }\n\n $scope.logoutFacebook = function() {\n logoutFacebookUser();\n };\n\n function loginFacebookUser() {\n return Auth.loginFacebook();\n }\n\n function logoutFacebookUser() {\n return Auth.logoutFacebook();\n }\n\n function getFacebookUserApi() {\n return Auth.getFacebookApi();\n }\n\n function getLoginUserStatus() {\n return Auth.getLoginStatus();\n }\n})" }, { "code": null, "e": 126055, "s": 125615, "text": "You are probably wondering why didn't we returned Auth service directly from the function expressions (first four functions). The reason for this is that you will probably want to add some more behavior after the Auth function is returned. You might send some data to your database, change the route after login, etc. This can be easily done by using JavaScript then() method to handle all the asynchronous operations instead of callbacks." }, { "code": null, "e": 126186, "s": 126055, "text": "Now we need to allow users to interact with the app. Our HTML will contain four buttons for calling the four functions we created." }, { "code": null, "e": 126465, "s": 126186, "text": "<button class = \"button\" ng-click = \"loginFacebook()\">LOG IN</button>\n<button class = \"button\" ng-click = \"logoutFacebook()\">LOG OUT</button>\n<button class = \"button\" ng-click = \"checkLoginStatus()\">CHECK</button>\n<button class = \"button\" ng-click = \"facebookAPI()\">API</button>" }, { "code": null, "e": 126606, "s": 126465, "text": "When the user taps the LOG IN button, the Facebook screen will appear. The user will be redirected to the app after the login is successful." }, { "code": null, "e": 126711, "s": 126606, "text": "The Cordova InAppBrowser plugin is used to open external links from your app inside a web browser view. " }, { "code": null, "e": 126850, "s": 126711, "text": "It is very easy to start working with this plugin. All you need to do is to open the command prompt window and install the Cordova plugin." }, { "code": null, "e": 126934, "s": 126850, "text": "C:\\Users\\Username\\Desktop\\MyApp>cordova plugin add org.apache.cordova.inappbrowser\n" }, { "code": null, "e": 127108, "s": 126934, "text": "This step allows us to start using the inAppBrowser. We can now create a button that will lead us to some external link, and add a simple function for triggering the plugin." }, { "code": null, "e": 127183, "s": 127108, "text": "<button class = \"button\" ng-click = \"openBrowser()\">OPEN BROWSER</button>\n" }, { "code": null, "e": 127587, "s": 127183, "text": ".controller('MyCtrl', function($scope, $cordovaInAppBrowser) {\n var options = {\n location: 'yes',\n clearcache: 'yes',\n toolbar: 'no'\n };\n \n $scope.openBrowser = function() {\n $cordovaInAppBrowser.open('http://ngcordova.com', '_blank', options)\n\t\t\n .then(function(event) {\n // success\n })\n\t\t\n .catch(function(event) {\n // error\n });\n }\n})" }, { "code": null, "e": 127665, "s": 127587, "text": "When the user taps the button the InAppBrowser will open the URL we provided." }, { "code": null, "e": 127759, "s": 127665, "text": "Several other methods can be used with this plugin, some of which are in the following table." }, { "code": null, "e": 127828, "s": 127759, "text": "This plugin also offers events that can be combined with $rootScope." }, { "code": null, "e": 127897, "s": 127828, "text": "This plugin is used for adding native audio sounds to the Ionic app." }, { "code": null, "e": 128016, "s": 127897, "text": "To be able to use this plugin, we first need to install it. Open the command prompt window and add the Cordova plugin." }, { "code": null, "e": 128095, "s": 128016, "text": "C:\\Users\\Username\\Desktop\\MyApp>cordova plugin add cordova-plugin-nativeaudio\n" }, { "code": null, "e": 128265, "s": 128095, "text": "Before we start using this plugin, we will need audio file. For simplicity, we will save our click.mp3 file inside the js folder, but you can place it wherever you want." }, { "code": null, "e": 128354, "s": 128265, "text": "The next step is to preload the audio file. There are two options available, which are −" }, { "code": null, "e": 128425, "s": 128354, "text": "preloadSimple − It is used for simple sounds that will be played once." }, { "code": null, "e": 128496, "s": 128425, "text": "preloadSimple − It is used for simple sounds that will be played once." }, { "code": null, "e": 128589, "s": 128496, "text": "preloadComplex − It is for sounds that will be played as looping sounds or background audio." }, { "code": null, "e": 128682, "s": 128589, "text": "preloadComplex − It is for sounds that will be played as looping sounds or background audio." }, { "code": null, "e": 128841, "s": 128682, "text": "Add the following code to your controller to preload an audio file. We need to be sure that the Ionic platform is loaded before we can preload the audio file." }, { "code": null, "e": 129233, "s": 128841, "text": "$ionicPlatform.ready(function() {\n $cordovaNativeAudio\n .preloadSimple('click', 'js/click.mp3')\n\t\n .then(function (msg) {\n console.log(msg);\n }, function (error) {\n console.log(error);\n });\n\n $cordovaNativeAudio.preloadComplex('click', 'js/click.mp3', 1, 1)\n\t.then(function (msg) {\n console.log(msg);\n }, function (error) {\n console.error(error);\n });\n});" }, { "code": null, "e": 129370, "s": 129233, "text": "In the same controller, we will add code for playing audio. Our $timeout function will stop and unload looping audio after five seconds." }, { "code": null, "e": 129642, "s": 129370, "text": "$scope.playAudio = function () {\n $cordovaNativeAudio.play('click');\n};\n\n$scope.loopAudio = function () {\n $cordovaNativeAudio.loop('click');\n\n $timeout(function () {\n $cordovaNativeAudio.stop('click');\n $cordovaNativeAudio.unload('click');\n }, 5000);\n}" }, { "code": null, "e": 129717, "s": 129642, "text": "The last thing we need is to create buttons for playing and looping audio." }, { "code": null, "e": 129846, "s": 129717, "text": "<button class = \"button\" ng-click = \"playAudio()\">PLAY</button>\n\n<button class = \"button\" ng-click = \"loopAudio()\">LOOP</button>" }, { "code": null, "e": 130048, "s": 129846, "text": "When we tap on play button, we will hear the sound once and when we tap on the loop button, the sound will loop for five seconds and then stop. This plugin works only on an emulator or a mobile device." }, { "code": null, "e": 130118, "s": 130048, "text": "This plugin is used for adding a geolocation plugin to the Ionic app." }, { "code": null, "e": 130234, "s": 130118, "text": "There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window." }, { "code": null, "e": 130313, "s": 130234, "text": "C:\\Users\\Username\\Desktop\\MyApp>cordova plugin add cordova-plugin-geolocation\n" }, { "code": null, "e": 130621, "s": 130313, "text": "The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPosition method that will return the current position of the device when the position is changed." }, { "code": null, "e": 131430, "s": 130621, "text": ".controller('MyCtrl', function($scope, $cordovaGeolocation) {\n var posOptions = {timeout: 10000, enableHighAccuracy: false};\n $cordovaGeolocation\n .getCurrentPosition(posOptions)\n\t\n .then(function (position) {\n var lat = position.coords.latitude\n var long = position.coords.longitude\n console.log(lat + ' ' + long)\n }, function(err) {\n console.log(err)\n });\n\n var watchOptions = {timeout : 3000, enableHighAccuracy: false};\n var watch = $cordovaGeolocation.watchPosition(watchOptions);\n\t\n watch.then(\n null,\n\t\t\n function(err) {\n console.log(err)\n },\n\t function(position) {\n var lat = position.coords.latitude\n var long = position.coords.longitude\n console.log(lat + '' + long)\n }\n );\n\n watch.clearWatch();\n})" }, { "code": null, "e": 131877, "s": 131430, "text": "You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option." }, { "code": null, "e": 132042, "s": 131877, "text": "When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change." }, { "code": null, "e": 132112, "s": 132042, "text": "This plugin allows us to record and playback audio files on a device." }, { "code": null, "e": 132230, "s": 132112, "text": "As with all the other Cordova plugins, the first thing we need to do is to install it from the command prompt window." }, { "code": null, "e": 132303, "s": 132230, "text": "C:\\Users\\Username\\Desktop\\MyApp>cordova plugin add cordova-plugin-media\n" }, { "code": null, "e": 132548, "s": 132303, "text": "Now, we are ready to use the plugin. In the following code sample, src is the source mp3 file that we will use for this tutorial. It is placed in js folder, but we need to add /android_asset/www/ before it, so it can be used on android devices." }, { "code": null, "e": 132855, "s": 132548, "text": "The complete functionality is wrapped inside the $ionicPlatform.ready() function to assure that everything is loaded before the plugin is used. After that, we are creating the media object by using the newMedia(src) method. The media object is used for adding play, pause, stop and release functionalities." }, { "code": null, "e": 133363, "s": 132855, "text": ".controller('MyCtrl', function($scope, $ionicPlatform, $cordovaMedia) {\n $ionicPlatform.ready(function() {\n var src = \"/android_asset/www/js/song.mp3\";\n var media = $cordovaMedia.newMedia(src);\n\n $scope.playMedia = function() {\n media.play();\n };\n\n $scope.pauseMedia = function() {\n media.pause();\n };\n\n $scope.stopMedia = function() {\n media.stop();\n };\n\n $scope.$on('destroy', function() {\n media.release();\n });\n });\n}" }, { "code": null, "e": 133441, "s": 133363, "text": "We will also create three buttons for calling play, pause and stop functions." }, { "code": null, "e": 133637, "s": 133441, "text": "<button class = \"button\" ng-click = \"playMedia()\">PLAY</button>\n\n<button class = \"button\" ng-click = \"pauseMedia()\">PAUSE</button>\n\n<button class = \"button\" ng-click = \"stopMedia()\">STOP</button>" }, { "code": null, "e": 133787, "s": 133637, "text": "We need to run it on an emulator or a mobile device for this plugin to work. When the user’s tap on the play button, the song.mp3 will start playing." }, { "code": null, "e": 133938, "s": 133787, "text": "You can see in the above example that we use src as an option parameter. There are other optional parameters that can be used for the newMedia method." }, { "code": null, "e": 134007, "s": 133938, "text": "The following table will show all the optional parameters available." }, { "code": null, "e": 134059, "s": 134007, "text": "The next table will show all the methods available." }, { "code": null, "e": 134116, "s": 134059, "text": "The following table will show all the methods available." }, { "code": null, "e": 134316, "s": 134116, "text": "Every mobile app needs an icon and splash screen. Ionic provides excellent solution for adding it and requires minimum work for the developers. Cropping and resizing is automated on the Ionic server." }, { "code": null, "e": 134588, "s": 134316, "text": "In the earlier chapters, we have discussed how to add different platforms for the Ionic app. By adding a platform, Ionic will install Cordova splash screen plugin for that platform so we do not need to install anything afterwards. All we need to do is to find two images." }, { "code": null, "e": 134996, "s": 134588, "text": "The images should be png, psd or ai files. The minimum dimension should be 192x192 for icon image and 2208×2208 for the splash screen image. This dimensions will cover all the devices. In our example, we will use the same image for both. The images need to be saved to resources folder instead of the default ones. After we are done with it, all we need is to run the following in the command prompt window." }, { "code": null, "e": 135045, "s": 134996, "text": "C:\\Users\\Username\\Desktop\\MyApp>ionic resources\n" }, { "code": null, "e": 135358, "s": 135045, "text": "Now, if you check resources/android or resources/ios folders, you will see that the images we added before are resized and cropped to accommodate different screen sizes. When we run our app on the device, we will see a splash screen before the app is started and we will see that a default Ionic icon is changed." }, { "code": null, "e": 135509, "s": 135358, "text": "NOTE − If you want to use different images for Android and iOS, you can add it to resources/android and resources/ios instead of the resources folder." }, { "code": null, "e": 135544, "s": 135509, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 135561, "s": 135544, "text": " Frahaan Hussain" }, { "code": null, "e": 135598, "s": 135561, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 135614, "s": 135598, "text": " Nikhil Agarwal" }, { "code": null, "e": 135621, "s": 135614, "text": " Print" }, { "code": null, "e": 135632, "s": 135621, "text": " Add Notes" } ]
Java Program to Check if a given matrix is sparse or not - GeeksforGeeks
13 Jan, 2022 A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4 6 0 0 Output : Yes There are 5 zeros. This count is more than half of matrix size. Input : 1 2 3 0 7 8 5 0 7 Output: No To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. Java // Java code to check // if a matrix is// sparse. import java.io.*; class GFG { static int MAX = 100; static boolean isSparse(int array[][], int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void main(String args[]) { int array[][] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// Nikita Tiwari. Output: Yes Please refer complete article on Check if a given matrix is sparse or not for more details! Java Java Programs Matrix Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array 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?
[ { "code": null, "e": 23635, "s": 23607, "text": "\n13 Jan, 2022" }, { "code": null, "e": 23955, "s": 23635, "text": "A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix," }, { "code": null, "e": 23966, "s": 23955, "text": "Examples: " }, { "code": null, "e": 24141, "s": 23966, "text": "Input : 1 0 3\n 0 0 4\n 6 0 0\nOutput : Yes\nThere are 5 zeros. This count\nis more than half of matrix\nsize.\n\nInput : 1 2 3\n 0 7 8\n 5 0 7 \nOutput: No " }, { "code": null, "e": 24317, "s": 24141, "text": "To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. " }, { "code": null, "e": 24322, "s": 24317, "text": "Java" }, { "code": "// Java code to check // if a matrix is// sparse. import java.io.*; class GFG { static int MAX = 100; static boolean isSparse(int array[][], int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void main(String args[]) { int array[][] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// Nikita Tiwari.", "e": 25191, "s": 24322, "text": null }, { "code": null, "e": 25201, "s": 25191, "text": "Output: " }, { "code": null, "e": 25205, "s": 25201, "text": "Yes" }, { "code": null, "e": 25297, "s": 25205, "text": "Please refer complete article on Check if a given matrix is sparse or not for more details!" }, { "code": null, "e": 25302, "s": 25297, "text": "Java" }, { "code": null, "e": 25316, "s": 25302, "text": "Java Programs" }, { "code": null, "e": 25323, "s": 25316, "text": "Matrix" }, { "code": null, "e": 25330, "s": 25323, "text": "Matrix" }, { "code": null, "e": 25335, "s": 25330, "text": "Java" }, { "code": null, "e": 25433, "s": 25335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25442, "s": 25433, "text": "Comments" }, { "code": null, "e": 25455, "s": 25442, "text": "Old Comments" }, { "code": null, "e": 25485, "s": 25455, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25500, "s": 25485, "text": "Stream In Java" }, { "code": null, "e": 25521, "s": 25500, "text": "Constructors in Java" }, { "code": null, "e": 25567, "s": 25521, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25586, "s": 25567, "text": "Exceptions in Java" }, { "code": null, "e": 25630, "s": 25586, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 25656, "s": 25630, "text": "Java Programming Examples" }, { "code": null, "e": 25690, "s": 25656, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 25737, "s": 25690, "text": "Implementing a Linked List in Java using Class" } ]
C# | Char.IsUpper() Method - GeeksforGeeks
01 Feb, 2019 In C#, Char.IsUpper() is a System.Char struct method which is used to check whether a Unicode character can be categorized as an uppercase letter or not. Valid uppercase letters will be the members of the UnicodeCategory: UppercaseLetter. This method can be overloaded by passing different type and number of arguments to it. Char.IsUpper(Char) MethodChar.IsUpper(String, Int32) Method Char.IsUpper(Char) Method Char.IsUpper(String, Int32) Method This method is used to check whether the specified Unicode character matches any uppercase letter or not. If it matches then it returns True otherwise return False. Syntax: public static bool IsUpper(char ch); Parameter: ch: It is required Unicode character of System.char type which is to be checked. Return Type: The method returns True, if it successfully matches any uppercase letter, otherwise returns False. The return type of this method is System.Boolean. Example: // C# program to illustrate the// Char.IsUpper(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if G is a // uppercase letter or not char ch1 = 'G'; result = Char.IsUpper(ch1); Console.WriteLine(result); // checking if 'g' is a // uppercase letter or not char ch2 = 'g'; result = Char.IsUpper(ch2); Console.WriteLine(result); }} True False This method is used to check whether the specified string at specified position matches with any uppercase letter or not. If it matches then it returns True otherwise returns False. Syntax: public static bool IsUpper(string str, int index); Parameters: Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32. Return Type: The method returns True if it successfully matches any uppercase letter at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean. Exceptions: If the value of str is null then this method will give ArgumentNullException If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException. Example: // C# program to illustrate the// Char.IsUpper(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for uppercase letter in // a string at a desired position string str1 = "GeeksForGeeks"; result = Char.IsUpper(str1, 5); Console.WriteLine(result); // checking for uppercase letter in a // string at a desired position string str2 = "geeksforgeeks"; result = Char.IsUpper(str2, 2); Console.WriteLine(result); }} True False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsUpper?view=netframework-4.7.2 CSharp-Char-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | Method Overriding C# | IsNullOrEmpty() Method C# Dictionary with examples String.Split() Method in C# with Examples Difference between Ref and Out keywords in C# C# | Arrays of Strings C# | Delegates Top 50 C# Interview Questions & Answers
[ { "code": null, "e": 23271, "s": 23243, "text": "\n01 Feb, 2019" }, { "code": null, "e": 23597, "s": 23271, "text": "In C#, Char.IsUpper() is a System.Char struct method which is used to check whether a Unicode character can be categorized as an uppercase letter or not. Valid uppercase letters will be the members of the UnicodeCategory: UppercaseLetter. This method can be overloaded by passing different type and number of arguments to it." }, { "code": null, "e": 23657, "s": 23597, "text": "Char.IsUpper(Char) MethodChar.IsUpper(String, Int32) Method" }, { "code": null, "e": 23683, "s": 23657, "text": "Char.IsUpper(Char) Method" }, { "code": null, "e": 23718, "s": 23683, "text": "Char.IsUpper(String, Int32) Method" }, { "code": null, "e": 23883, "s": 23718, "text": "This method is used to check whether the specified Unicode character matches any uppercase letter or not. If it matches then it returns True otherwise return False." }, { "code": null, "e": 23891, "s": 23883, "text": "Syntax:" }, { "code": null, "e": 23928, "s": 23891, "text": "public static bool IsUpper(char ch);" }, { "code": null, "e": 23939, "s": 23928, "text": "Parameter:" }, { "code": null, "e": 24020, "s": 23939, "text": "ch: It is required Unicode character of System.char type which is to be checked." }, { "code": null, "e": 24182, "s": 24020, "text": "Return Type: The method returns True, if it successfully matches any uppercase letter, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 24191, "s": 24182, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsUpper(Char) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking if G is a // uppercase letter or not char ch1 = 'G'; result = Char.IsUpper(ch1); Console.WriteLine(result); // checking if 'g' is a // uppercase letter or not char ch2 = 'g'; result = Char.IsUpper(ch2); Console.WriteLine(result); }}", "e": 24710, "s": 24191, "text": null }, { "code": null, "e": 24722, "s": 24710, "text": "True\nFalse\n" }, { "code": null, "e": 24904, "s": 24722, "text": "This method is used to check whether the specified string at specified position matches with any uppercase letter or not. If it matches then it returns True otherwise returns False." }, { "code": null, "e": 24912, "s": 24904, "text": "Syntax:" }, { "code": null, "e": 24963, "s": 24912, "text": "public static bool IsUpper(string str, int index);" }, { "code": null, "e": 24975, "s": 24963, "text": "Parameters:" }, { "code": null, "e": 25160, "s": 24975, "text": "Str: It is the required string of System.String type which is to be evaluate.index: It is the position of character in string to be compared and type of this parameter is System.Int32." }, { "code": null, "e": 25368, "s": 25160, "text": "Return Type: The method returns True if it successfully matches any uppercase letter at the specified index in the specified string, otherwise returns False. The return type of this method is System.Boolean." }, { "code": null, "e": 25380, "s": 25368, "text": "Exceptions:" }, { "code": null, "e": 25457, "s": 25380, "text": "If the value of str is null then this method will give ArgumentNullException" }, { "code": null, "e": 25585, "s": 25457, "text": "If the index is less than zero or greater than the last position in str then this method will give ArgumentOutOfRangeException." }, { "code": null, "e": 25594, "s": 25585, "text": "Example:" }, { "code": "// C# program to illustrate the// Char.IsUpper(String, Int32) Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; // checking for uppercase letter in // a string at a desired position string str1 = \"GeeksForGeeks\"; result = Char.IsUpper(str1, 5); Console.WriteLine(result); // checking for uppercase letter in a // string at a desired position string str2 = \"geeksforgeeks\"; result = Char.IsUpper(str2, 2); Console.WriteLine(result); }}", "e": 26200, "s": 25594, "text": null }, { "code": null, "e": 26212, "s": 26200, "text": "True\nFalse\n" }, { "code": null, "e": 26311, "s": 26212, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.IsUpper?view=netframework-4.7.2" }, { "code": null, "e": 26330, "s": 26311, "text": "CSharp-Char-Struct" }, { "code": null, "e": 26344, "s": 26330, "text": "CSharp-method" }, { "code": null, "e": 26347, "s": 26344, "text": "C#" }, { "code": null, "e": 26445, "s": 26347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26454, "s": 26445, "text": "Comments" }, { "code": null, "e": 26467, "s": 26454, "text": "Old Comments" }, { "code": null, "e": 26521, "s": 26467, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 26583, "s": 26521, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 26606, "s": 26583, "text": "C# | Method Overriding" }, { "code": null, "e": 26634, "s": 26606, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 26662, "s": 26634, "text": "C# Dictionary with examples" }, { "code": null, "e": 26704, "s": 26662, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 26750, "s": 26704, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26773, "s": 26750, "text": "C# | Arrays of Strings" }, { "code": null, "e": 26788, "s": 26773, "text": "C# | Delegates" } ]
How to convert a CLOB type to String in Java?
CLOB stands for Character Large Object in general, an SQL Clob is a built-in datatype and is used to store large amount of textual data. Using this datatype, you can store data up to 2,147,483,647 characters. The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the data). MySQL database provides support for this data type using four variables namely, TINYTEXT, TEXT, MEDIUMTEXT and, LONGTEXT. Retrieve the Clob value from a table using the getClob() or getCharacterStream() method of the PresparedStatement interface. Reader r = clob.getCharacterStream(); Read each character one by one from the retrieved Stream of characters and append them to the StringBuilder or StringBuffer. int j = 0; StringBuffer buffer = new StringBuffer(); int ch; while ((ch = r.read())!=-1) { buffer.append(""+(char)ch); } System.out.println(buffer.toString()); j++; Finally, display or stored the obtained String. System.out.println(buffer.toString()); Let us create a table with name technologies_data in MySQL database using the following query − CREATE TABLE Technologies (Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT); The third column of the table Article stores the data of type CLOB. Following JDBC program initially inserts 5 records in the technologies_data table storing text file (contents of it) it to the article column (CLOB type). Then, it retrieves the records of the table and, displays the name and contents of the article. Here, we are trying to converting the data of the retrieved CLOB into String and display it. import java.io.FileReader; import java.io.Reader; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class ClobToString { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampledatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Inserting values String query = "INSERT INTO Technologies_data VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "JavaFX"); pstmt.setString(2, "Java Library"); FileReader reader = new FileReader("E:\\images\\javafx_contents.txt"); pstmt.setClob(3, reader); pstmt.execute(); pstmt.setString(1, "CoffeeScript"); pstmt.setString(2, "Scripting Language"); reader = new FileReader("E:\\images\\coffeescript_contents.txt"); pstmt.setClob(3, reader); pstmt.execute(); pstmt.setString(1, "Cassandra"); pstmt.setString(2, "NoSQL Database"); reader = new FileReader("E:\\images\\cassandra_contents.txt"); pstmt.setClob(3, reader); pstmt.execute(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from Technologies_data"); System.out.println("Contents of the table are: "); while(rs.next()) { System.out.println("Article: "+rs.getString("Name")); Clob clob = rs.getClob("Article"); Reader r = clob.getCharacterStream(); StringBuffer buffer = new StringBuffer(); int ch; while ((ch = r.read())!=-1) { buffer.append(""+(char)ch); } System.out.println("Contents: "+buffer.toString()); System.out.println(" "); } } } Connection established...... Contents of the table are: Article: JavaFX Contents: JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%. Article: CoffeeScript Contents: CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language. Article: Cassandra Contents: Apache Cassandra is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. It is a type of NoSQL database. Let us first understand what a NoSQL database does.
[ { "code": null, "e": 1271, "s": 1062, "text": "CLOB stands for Character Large Object in general, an SQL Clob is a built-in datatype and is used to store large amount of textual data. Using this datatype, you can store data up to 2,147,483,647 characters." }, { "code": null, "e": 1471, "s": 1271, "text": "The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the data)." }, { "code": null, "e": 1593, "s": 1471, "text": "MySQL database provides support for this data type using four variables namely, TINYTEXT, TEXT, MEDIUMTEXT and, LONGTEXT." }, { "code": null, "e": 1718, "s": 1593, "text": "Retrieve the Clob value from a table using the getClob() or getCharacterStream() method of the PresparedStatement interface." }, { "code": null, "e": 1756, "s": 1718, "text": "Reader r = clob.getCharacterStream();" }, { "code": null, "e": 1881, "s": 1756, "text": "Read each character one by one from the retrieved Stream of characters and append them to the StringBuilder or StringBuffer." }, { "code": null, "e": 2049, "s": 1881, "text": "int j = 0;\nStringBuffer buffer = new StringBuffer();\nint ch;\nwhile ((ch = r.read())!=-1) {\n buffer.append(\"\"+(char)ch);\n}\nSystem.out.println(buffer.toString());\nj++;" }, { "code": null, "e": 2097, "s": 2049, "text": "Finally, display or stored the obtained String." }, { "code": null, "e": 2136, "s": 2097, "text": "System.out.println(buffer.toString());" }, { "code": null, "e": 2232, "s": 2136, "text": "Let us create a table with name technologies_data in MySQL database using the following query −" }, { "code": null, "e": 2316, "s": 2232, "text": "CREATE TABLE Technologies (Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT);" }, { "code": null, "e": 2384, "s": 2316, "text": "The third column of the table Article stores the data of type CLOB." }, { "code": null, "e": 2539, "s": 2384, "text": "Following JDBC program initially inserts 5 records in the technologies_data table storing text file (contents of it) it to the article column (CLOB type)." }, { "code": null, "e": 2728, "s": 2539, "text": "Then, it retrieves the records of the table and, displays the name and contents of the article. Here, we are trying to converting the data of the retrieved CLOB into String and display it." }, { "code": null, "e": 4849, "s": 2728, "text": "import java.io.FileReader;\nimport java.io.Reader;\nimport java.sql.Clob;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class ClobToString {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampledatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Inserting values\n String query = \"INSERT INTO Technologies_data VALUES (?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"JavaFX\");\n pstmt.setString(2, \"Java Library\");\n FileReader reader = new FileReader(\"E:\\\\images\\\\javafx_contents.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n pstmt.setString(1, \"CoffeeScript\");\n pstmt.setString(2, \"Scripting Language\");\n reader = new FileReader(\"E:\\\\images\\\\coffeescript_contents.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n pstmt.setString(1, \"Cassandra\");\n pstmt.setString(2, \"NoSQL Database\");\n reader = new FileReader(\"E:\\\\images\\\\cassandra_contents.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from Technologies_data\");\n System.out.println(\"Contents of the table are: \");\n while(rs.next()) {\n System.out.println(\"Article: \"+rs.getString(\"Name\"));\n Clob clob = rs.getClob(\"Article\");\n Reader r = clob.getCharacterStream();\n StringBuffer buffer = new StringBuffer();\n int ch;\n while ((ch = r.read())!=-1) {\n buffer.append(\"\"+(char)ch);\n }\n System.out.println(\"Contents: \"+buffer.toString());\n System.out.println(\" \");\n }\n }\n}" }, { "code": null, "e": 5727, "s": 4849, "text": "Connection established......\nContents of the table are:\nArticle: JavaFX\nContents: JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%.\nArticle: CoffeeScript\nContents: CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.\nArticle: Cassandra\nContents: Apache Cassandra is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers,\nproviding high availability with no single point of failure. It is a type of NoSQL database. Let us first understand what a NoSQL database does." } ]
R - Decision Tree
Decision tree is a graph to represent choices and their results in form of a tree. The nodes in the graph represent an event or choice and the edges of the graph represent the decision rules or conditions. It is mostly used in Machine Learning and Data Mining applications using R. Examples of use of decision tress is − predicting an email as spam or not spam, predicting of a tumor is cancerous or predicting a loan as a good or bad credit risk based on the factors in each of these. Generally, a model is created with observed data also called training data. Then a set of validation data is used to verify and improve the model. R has packages which are used to create and visualize decision trees. For new set of predictor variable, we use this model to arrive at a decision on the category (yes/No, spam/not spam) of the data. The R package "party" is used to create decision trees. Use the below command in R console to install the package. You also have to install the dependent packages if any. install.packages("party") The package "party" has the function ctree() which is used to create and analyze decison tree. The basic syntax for creating a decision tree in R is − ctree(formula, data) Following is the description of the parameters used − formula is a formula describing the predictor and response variables. formula is a formula describing the predictor and response variables. data is the name of the data set used. data is the name of the data set used. We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables "age","shoesize","score" and whether the person is a native speaker or not. Here is the sample data. # Load the party package. It will automatically load other # dependent packages. library(party) # Print some records from data set readingSkills. print(head(readingSkills)) When we execute the above code, it produces the following result and chart − nativeSpeaker age shoeSize score 1 yes 5 24.83189 32.29385 2 yes 6 25.95238 36.63105 3 no 11 30.42170 49.60593 4 yes 7 28.66450 40.28456 5 yes 11 31.88207 55.46085 6 yes 10 30.07843 52.83124 Loading required package: methods Loading required package: grid ............................... ............................... We will use the ctree() function to create the decision tree and see its graph. # Load the party package. It will automatically load other # dependent packages. library(party) # Create the input data frame. input.dat <- readingSkills[c(1:105),] # Give the chart file a name. png(file = "decision_tree.png") # Create the tree. output.tree <- ctree( nativeSpeaker ~ age + shoeSize + score, data = input.dat) # Plot the tree. plot(output.tree) # Save the file. dev.off() When we execute the above code, it produces the following result − null device 1 Loading required package: methods Loading required package: grid Loading required package: mvtnorm Loading required package: modeltools Loading required package: stats4 Loading required package: strucchange Loading required package: zoo Attaching package: ‘zoo’ The following objects are masked from ‘package:base’: as.Date, as.Date.numeric Loading required package: sandwich From the decision tree shown above we can conclude that anyone whose readingSkills score is less than 38.3 and age is more than 6 is not a native Speaker. 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2684, "s": 2402, "text": "Decision tree is a graph to represent choices and their results in form of a tree. The nodes in the graph represent an event or choice and the edges of the graph represent the decision rules or conditions. It is mostly used in Machine Learning and Data Mining applications using R." }, { "code": null, "e": 3235, "s": 2684, "text": "Examples of use of decision tress is − predicting an email as spam or not spam, predicting of a tumor is cancerous or predicting a loan as a good or bad credit risk based on the factors in each of these. Generally, a model is created with observed data also called training data. Then a set of validation data is used to verify and improve the model. R has packages which are used to create and visualize decision trees. For new set of predictor variable, we use this model to arrive at a decision on the category (yes/No, spam/not spam) of the data." }, { "code": null, "e": 3291, "s": 3235, "text": "The R package \"party\" is used to create decision trees." }, { "code": null, "e": 3406, "s": 3291, "text": "Use the below command in R console to install the package. You also have to install the dependent packages if any." }, { "code": null, "e": 3433, "s": 3406, "text": "install.packages(\"party\")\n" }, { "code": null, "e": 3528, "s": 3433, "text": "The package \"party\" has the function ctree() which is used to create and analyze decison tree." }, { "code": null, "e": 3584, "s": 3528, "text": "The basic syntax for creating a decision tree in R is −" }, { "code": null, "e": 3606, "s": 3584, "text": "ctree(formula, data)\n" }, { "code": null, "e": 3660, "s": 3606, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3730, "s": 3660, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 3800, "s": 3730, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 3839, "s": 3800, "text": "data is the name of the data set used." }, { "code": null, "e": 3878, "s": 3839, "text": "data is the name of the data set used." }, { "code": null, "e": 4112, "s": 3878, "text": "We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables \"age\",\"shoesize\",\"score\" and whether the person is a native speaker or not." }, { "code": null, "e": 4137, "s": 4112, "text": "Here is the sample data." }, { "code": null, "e": 4311, "s": 4137, "text": "# Load the party package. It will automatically load other\n# dependent packages.\nlibrary(party)\n\n# Print some records from data set readingSkills.\nprint(head(readingSkills))" }, { "code": null, "e": 4388, "s": 4311, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 4826, "s": 4388, "text": " nativeSpeaker age shoeSize score\n1 yes 5 24.83189 32.29385\n2 yes 6 25.95238 36.63105\n3 no 11 30.42170 49.60593\n4 yes 7 28.66450 40.28456\n5 yes 11 31.88207 55.46085\n6 yes 10 30.07843 52.83124\nLoading required package: methods\nLoading required package: grid\n...............................\n...............................\n" }, { "code": null, "e": 4906, "s": 4826, "text": "We will use the ctree() function to create the decision tree and see its graph." }, { "code": null, "e": 5306, "s": 4906, "text": "# Load the party package. It will automatically load other\n# dependent packages.\nlibrary(party)\n\n# Create the input data frame.\ninput.dat <- readingSkills[c(1:105),]\n\n# Give the chart file a name.\npng(file = \"decision_tree.png\")\n\n# Create the tree.\n output.tree <- ctree(\n nativeSpeaker ~ age + shoeSize + score, \n data = input.dat)\n\n# Plot the tree.\nplot(output.tree)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 5373, "s": 5306, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5783, "s": 5373, "text": "null device \n 1 \nLoading required package: methods\nLoading required package: grid\nLoading required package: mvtnorm\nLoading required package: modeltools\nLoading required package: stats4\nLoading required package: strucchange\nLoading required package: zoo\n\nAttaching package: ‘zoo’\n\nThe following objects are masked from ‘package:base’:\n\n as.Date, as.Date.numeric\n\nLoading required package: sandwich\n" }, { "code": null, "e": 5938, "s": 5783, "text": "From the decision tree shown above we can conclude that anyone whose readingSkills score is less than 38.3 and age is more than 6 is not a native Speaker." }, { "code": null, "e": 5971, "s": 5938, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 5986, "s": 5971, "text": " Nishant Malik" }, { "code": null, "e": 6021, "s": 5986, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6036, "s": 6021, "text": " Nishant Malik" }, { "code": null, "e": 6071, "s": 6036, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6086, "s": 6071, "text": " Nishant Malik" }, { "code": null, "e": 6119, "s": 6086, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6133, "s": 6119, "text": " Asif Hussain" }, { "code": null, "e": 6168, "s": 6133, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6183, "s": 6168, "text": " Nishant Malik" }, { "code": null, "e": 6218, "s": 6183, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6232, "s": 6218, "text": " Asif Hussain" }, { "code": null, "e": 6239, "s": 6232, "text": " Print" }, { "code": null, "e": 6250, "s": 6239, "text": " Add Notes" } ]
Tk - Canvas Widgets
Canvas is used for providing drawing areas. The syntax for canvas widget is shown below − canvas canvasName options The options available for the canvas widget are listed below in the following table − -background color Used to set background color for widget. -closeenough distance Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value may be a fraction and must be positive. -scrollregion boundingBox The bounding box for the total area of this canvas. -height number Used to set height for widget. -width number Sets the width for widget. -xscrollincrement size The amount to scroll horizontally when scrolling is requested. -yscrollincrement size The amount to scroll vertically when scrolling is requested. A simple example for canvas widget is shown below − #!/usr/bin/wish canvas .myCanvas -background red -width 100 -height 100 pack .myCanvas When we run the above program, we will get the following output − The list of the available widgets for drawing in canvas is listed below − Draws a line. Draws an arc. Draws a rectangle. Draws an oval. Draws a polygon. Draws a text. Draws a bitmap. Draws an image. An example using different canvas widgets is shown below − #!/usr/bin/wish canvas .myCanvas -background red -width 200 -height 200 pack .myCanvas .myCanvas create arc 10 10 50 50 -fill yellow .myCanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true -splinesteps 2 .myCanvas create oval 50 50 100 80 -fill yellow .myCanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green .myCanvas create rectangle 150 150 170 170 -fill yellow .myCanvas create text 170 20 -fill yellow -text "Hello" -font {Helvetica -18 bold} .myCanvas create bitmap 180 50 -bitmap info When we run the above program, we will get the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2291, "s": 2201, "text": "Canvas is used for providing drawing areas. The syntax for canvas widget is shown below −" }, { "code": null, "e": 2318, "s": 2291, "text": "canvas canvasName options\n" }, { "code": null, "e": 2404, "s": 2318, "text": "The options available for the canvas widget are listed below in the following table −" }, { "code": null, "e": 2422, "s": 2404, "text": "-background color" }, { "code": null, "e": 2463, "s": 2422, "text": "Used to set background color for widget." }, { "code": null, "e": 2485, "s": 2463, "text": "-closeenough distance" }, { "code": null, "e": 2620, "s": 2485, "text": "Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value may be a fraction and must be positive." }, { "code": null, "e": 2646, "s": 2620, "text": "-scrollregion boundingBox" }, { "code": null, "e": 2698, "s": 2646, "text": "The bounding box for the total area of this canvas." }, { "code": null, "e": 2713, "s": 2698, "text": "-height number" }, { "code": null, "e": 2744, "s": 2713, "text": "Used to set height for widget." }, { "code": null, "e": 2758, "s": 2744, "text": "-width number" }, { "code": null, "e": 2785, "s": 2758, "text": "Sets the width for widget." }, { "code": null, "e": 2808, "s": 2785, "text": "-xscrollincrement size" }, { "code": null, "e": 2872, "s": 2808, "text": "The amount to scroll horizontally when scrolling is requested." }, { "code": null, "e": 2895, "s": 2872, "text": "-yscrollincrement size" }, { "code": null, "e": 2956, "s": 2895, "text": "The amount to scroll vertically when scrolling is requested." }, { "code": null, "e": 3008, "s": 2956, "text": "A simple example for canvas widget is shown below −" }, { "code": null, "e": 3097, "s": 3008, "text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 100 -height 100 \npack .myCanvas" }, { "code": null, "e": 3163, "s": 3097, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 3237, "s": 3163, "text": "The list of the available widgets for drawing in canvas is listed below −" }, { "code": null, "e": 3251, "s": 3237, "text": "Draws a line." }, { "code": null, "e": 3265, "s": 3251, "text": "Draws an arc." }, { "code": null, "e": 3284, "s": 3265, "text": "Draws a rectangle." }, { "code": null, "e": 3299, "s": 3284, "text": "Draws an oval." }, { "code": null, "e": 3316, "s": 3299, "text": "Draws a polygon." }, { "code": null, "e": 3330, "s": 3316, "text": "Draws a text." }, { "code": null, "e": 3346, "s": 3330, "text": "Draws a bitmap." }, { "code": null, "e": 3362, "s": 3346, "text": "Draws an image." }, { "code": null, "e": 3421, "s": 3362, "text": "An example using different canvas widgets is shown below −" }, { "code": null, "e": 3968, "s": 3421, "text": "#!/usr/bin/wish\n\ncanvas .myCanvas -background red -width 200 -height 200 \npack .myCanvas\n.myCanvas create arc 10 10 50 50 -fill yellow\n.myCanvas create line 10 30 50 50 100 10 -arrow both -fill yellow -smooth true\n -splinesteps 2\n.myCanvas create oval 50 50 100 80 -fill yellow\n.myCanvas create polygon 50 150 100 80 120 120 100 190 -fill yellow -outline green\n.myCanvas create rectangle 150 150 170 170 -fill yellow\n.myCanvas create text 170 20 -fill yellow -text \"Hello\" -font {Helvetica -18 bold}\n.myCanvas create bitmap 180 50 -bitmap info" }, { "code": null, "e": 4034, "s": 3968, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 4041, "s": 4034, "text": " Print" }, { "code": null, "e": 4052, "s": 4041, "text": " Add Notes" } ]
Real Time Application(Twitter)
Let us analyze a real time application to get the latest twitter feeds and its hashtags. Earlier, we have seen integration of Storm and Spark with Kafka. In both the scenarios, we created a Kafka Producer (using cli) to send message to the Kafka ecosystem. Then, the storm and spark inte-gration reads the messages by using the Kafka consumer and injects it into storm and spark ecosystem respectively. So, practically we need to create a Kafka Producer, which should − Read the twitter feeds using “Twitter Streaming API”, Process the feeds, Extract the HashTags and Send it to Kafka. Once the HashTags are received by Kafka, the Storm / Spark integration receive the infor-mation and send it to Storm / Spark ecosystem. The “Twitter Streaming API” can be accessed in any programming language. The “twitter4j” is an open source, unofficial Java library, which provides a Java based module to easily access the “Twitter Streaming API”. The “twitter4j” provides a listener based framework to access the tweets. To access the “Twitter Streaming API”, we need to sign in for Twitter developer account and should get the following OAuth authentication details. Customerkey CustomerSecret AccessToken AccessTookenSecret Once the developer account is created, download the “twitter4j” jar files and place it in the java class path. The Complete Twitter Kafka producer coding (KafkaTwitterProducer.java) is listed below − import java.util.Arrays; import java.util.Properties; import java.util.concurrent.LinkedBlockingQueue; import twitter4j.*; import twitter4j.conf.*; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; public class KafkaTwitterProducer { public static void main(String[] args) throws Exception { LinkedBlockingQueue<Status> queue = new LinkedBlockingQueue<Sta-tus>(1000); if(args.length < 5){ System.out.println( "Usage: KafkaTwitterProducer <twitter-consumer-key> <twitter-consumer-secret> <twitter-access-token> <twitter-access-token-secret> <topic-name> <twitter-search-keywords>"); return; } String consumerKey = args[0].toString(); String consumerSecret = args[1].toString(); String accessToken = args[2].toString(); String accessTokenSecret = args[3].toString(); String topicName = args[4].toString(); String[] arguments = args.clone(); String[] keyWords = Arrays.copyOfRange(arguments, 5, arguments.length); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).get-Instance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(status); // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); // System.out.println("@" + status.getUser().getScreen-Name()); /*for(URLEntity urle : status.getURLEntities()) { System.out.println(urle.getDisplayURL()); }*/ /*for(HashtagEntity hashtage : status.getHashtagEntities()) { System.out.println(hashtage.getText()); }*/ } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletion-Notice) { // System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // System.out.println("Got track limitation notice:" + num-berOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { // System.out.println("Got scrub_geo event userId:" + userId + "upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { // System.out.println("Got stall warning:" + warning); } @Override public void onException(Exception ex) { ex.printStackTrace(); } }; twitterStream.addListener(listener); FilterQuery query = new FilterQuery().track(keyWords); twitterStream.filter(query); Thread.sleep(5000); //Add Kafka producer config settings Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("acks", "all"); props.put("retries", 0); props.put("batch.size", 16384); props.put("linger.ms", 1); props.put("buffer.memory", 33554432); props.put("key.serializer", "org.apache.kafka.common.serializa-tion.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serializa-tion.StringSerializer"); Producer<String, String> producer = new KafkaProducer<String, String>(props); int i = 0; int j = 0; while(i < 10) { Status ret = queue.poll(); if (ret == null) { Thread.sleep(100); i++; }else { for(HashtagEntity hashtage : ret.getHashtagEntities()) { System.out.println("Hashtag: " + hashtage.getText()); producer.send(new ProducerRecord<String, String>( top-icName, Integer.toString(j++), hashtage.getText())); } } } producer.close(); Thread.sleep(5000); twitterStream.shutdown(); } } Compile the application using the following command − javac -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:. KafkaTwitterProducer.java Open two consoles. Run the above compiled application as shown below in one console. java -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”: . KafkaTwitterProducer <twitter-consumer-key> <twitter-consumer-secret> <twitter-access-token> <twitter-ac-cess-token-secret> my-first-topic food Run any one of the Spark / Storm application explained in the previous chapter in another win-dow. The main point to note is that the topic used should be same in both cases. Here, we have used “my-first-topic” as the topic name. The output of this application will depend on the keywords and the current feed of the twitter. A sample output is specified below (storm integration). . . . food : 1 foodie : 2 burger : 1 . . . 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2437, "s": 1967, "text": "Let us analyze a real time application to get the latest twitter feeds and its hashtags. Earlier, we have seen integration of Storm and Spark with Kafka. In both the scenarios, we created a Kafka Producer (using cli) to send message to the Kafka ecosystem. Then, the storm and spark inte-gration reads the messages by using the Kafka consumer and injects it into storm and spark ecosystem respectively. So, practically we need to create a Kafka Producer, which should −" }, { "code": null, "e": 2491, "s": 2437, "text": "Read the twitter feeds using “Twitter Streaming API”," }, { "code": null, "e": 2510, "s": 2491, "text": "Process the feeds," }, { "code": null, "e": 2535, "s": 2510, "text": "Extract the HashTags and" }, { "code": null, "e": 2553, "s": 2535, "text": "Send it to Kafka." }, { "code": null, "e": 2689, "s": 2553, "text": "Once the HashTags are received by Kafka, the Storm / Spark integration receive the infor-mation and send it to Storm / Spark ecosystem." }, { "code": null, "e": 3124, "s": 2689, "text": "The “Twitter Streaming API” can be accessed in any programming language. The “twitter4j” is an open source, unofficial Java library, which provides a Java based module to easily access the “Twitter Streaming API”. The “twitter4j” provides a listener based framework to access the tweets. To access the “Twitter Streaming API”, we need to sign in for Twitter developer account and should get the following OAuth authentication details." }, { "code": null, "e": 3136, "s": 3124, "text": "Customerkey" }, { "code": null, "e": 3151, "s": 3136, "text": "CustomerSecret" }, { "code": null, "e": 3163, "s": 3151, "text": "AccessToken" }, { "code": null, "e": 3182, "s": 3163, "text": "AccessTookenSecret" }, { "code": null, "e": 3293, "s": 3182, "text": "Once the developer account is created, download the “twitter4j” jar files and place it in the java class path." }, { "code": null, "e": 3383, "s": 3293, "text": "The Complete Twitter Kafka producer coding (KafkaTwitterProducer.java) is listed below −" }, { "code": null, "e": 7991, "s": 3383, "text": "import java.util.Arrays;\nimport java.util.Properties;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport twitter4j.*;\nimport twitter4j.conf.*;\n\nimport org.apache.kafka.clients.producer.Producer;\nimport org.apache.kafka.clients.producer.KafkaProducer;\nimport org.apache.kafka.clients.producer.ProducerRecord;\n\npublic class KafkaTwitterProducer {\n public static void main(String[] args) throws Exception {\n LinkedBlockingQueue<Status> queue = new LinkedBlockingQueue<Sta-tus>(1000);\n \n if(args.length < 5){\n System.out.println(\n \"Usage: KafkaTwitterProducer <twitter-consumer-key>\n <twitter-consumer-secret> <twitter-access-token>\n <twitter-access-token-secret>\n <topic-name> <twitter-search-keywords>\");\n return;\n }\n \n String consumerKey = args[0].toString();\n String consumerSecret = args[1].toString();\n String accessToken = args[2].toString();\n String accessTokenSecret = args[3].toString();\n String topicName = args[4].toString();\n String[] arguments = args.clone();\n String[] keyWords = Arrays.copyOfRange(arguments, 5, arguments.length);\n\n ConfigurationBuilder cb = new ConfigurationBuilder();\n cb.setDebugEnabled(true)\n .setOAuthConsumerKey(consumerKey)\n .setOAuthConsumerSecret(consumerSecret)\n .setOAuthAccessToken(accessToken)\n .setOAuthAccessTokenSecret(accessTokenSecret);\n\n TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).get-Instance();\n StatusListener listener = new StatusListener() {\n \n @Override\n public void onStatus(Status status) { \n queue.offer(status);\n\n // System.out.println(\"@\" + status.getUser().getScreenName() \n + \" - \" + status.getText());\n // System.out.println(\"@\" + status.getUser().getScreen-Name());\n\n /*for(URLEntity urle : status.getURLEntities()) {\n System.out.println(urle.getDisplayURL());\n }*/\n\n /*for(HashtagEntity hashtage : status.getHashtagEntities()) {\n System.out.println(hashtage.getText());\n }*/\n }\n \n @Override\n public void onDeletionNotice(StatusDeletionNotice statusDeletion-Notice) {\n // System.out.println(\"Got a status deletion notice id:\" \n + statusDeletionNotice.getStatusId());\n }\n \n @Override\n public void onTrackLimitationNotice(int numberOfLimitedStatuses) {\n // System.out.println(\"Got track limitation notice:\" + \n num-berOfLimitedStatuses);\n }\n\n @Override\n public void onScrubGeo(long userId, long upToStatusId) {\n // System.out.println(\"Got scrub_geo event userId:\" + userId + \n \"upToStatusId:\" + upToStatusId);\n } \n \n @Override\n public void onStallWarning(StallWarning warning) {\n // System.out.println(\"Got stall warning:\" + warning);\n }\n \n @Override\n public void onException(Exception ex) {\n ex.printStackTrace();\n }\n };\n twitterStream.addListener(listener);\n \n FilterQuery query = new FilterQuery().track(keyWords);\n twitterStream.filter(query);\n\n Thread.sleep(5000);\n \n //Add Kafka producer config settings\n Properties props = new Properties();\n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"acks\", \"all\");\n props.put(\"retries\", 0);\n props.put(\"batch.size\", 16384);\n props.put(\"linger.ms\", 1);\n props.put(\"buffer.memory\", 33554432);\n \n props.put(\"key.serializer\", \n \"org.apache.kafka.common.serializa-tion.StringSerializer\");\n props.put(\"value.serializer\", \n \"org.apache.kafka.common.serializa-tion.StringSerializer\");\n \n Producer<String, String> producer = new KafkaProducer<String, String>(props);\n int i = 0;\n int j = 0;\n \n while(i < 10) {\n Status ret = queue.poll();\n \n if (ret == null) {\n Thread.sleep(100);\n i++;\n }else {\n for(HashtagEntity hashtage : ret.getHashtagEntities()) {\n System.out.println(\"Hashtag: \" + hashtage.getText());\n producer.send(new ProducerRecord<String, String>(\n top-icName, Integer.toString(j++), hashtage.getText()));\n }\n }\n }\n producer.close();\n Thread.sleep(5000);\n twitterStream.shutdown();\n }\n}" }, { "code": null, "e": 8045, "s": 7991, "text": "Compile the application using the following command −" }, { "code": null, "e": 8134, "s": 8045, "text": "javac -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:. KafkaTwitterProducer.java" }, { "code": null, "e": 8219, "s": 8134, "text": "Open two consoles. Run the above compiled application as shown below in one console." }, { "code": null, "e": 8426, "s": 8219, "text": "java -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:\n. KafkaTwitterProducer <twitter-consumer-key>\n<twitter-consumer-secret>\n<twitter-access-token>\n<twitter-ac-cess-token-secret>\nmy-first-topic food" }, { "code": null, "e": 8656, "s": 8426, "text": "Run any one of the Spark / Storm application explained in the previous chapter in another win-dow. The main point to note is that the topic used should be same in both cases. Here, we have used “my-first-topic” as the topic name." }, { "code": null, "e": 8808, "s": 8656, "text": "The output of this application will depend on the keywords and the current feed of the twitter. A sample output is specified below (storm integration)." }, { "code": null, "e": 8852, "s": 8808, "text": ". . .\nfood : 1\nfoodie : 2\nburger : 1\n. . .\n" }, { "code": null, "e": 8887, "s": 8852, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8906, "s": 8887, "text": " Arnab Chakraborty" }, { "code": null, "e": 8941, "s": 8906, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8962, "s": 8941, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8995, "s": 8962, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 9008, "s": 8995, "text": " Nilay Mehta" }, { "code": null, "e": 9043, "s": 9008, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9061, "s": 9043, "text": " Bigdata Engineer" }, { "code": null, "e": 9094, "s": 9061, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9112, "s": 9094, "text": " Bigdata Engineer" }, { "code": null, "e": 9145, "s": 9112, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 9163, "s": 9145, "text": " Bigdata Engineer" }, { "code": null, "e": 9170, "s": 9163, "text": " Print" }, { "code": null, "e": 9181, "s": 9170, "text": " Add Notes" } ]
How to put a ListView into a ScrollView without it collapsing on Android in Kotlin?
This example demonstrates how to put a ListView into a ScrollView without it collapsing on Android in 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"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> </ScrollView> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.ArrayAdapter import android.widget.ListView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private val listViewArray = arrayOf( "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen" ) lateinit var list: ListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp"; list = findViewById(R.id.listView) list.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listViewArray) ListHelper.getListViewSize(list) } } Step 4 − Create a new Kotlin class ListHelper.kt and add the following code import android.util.Log import android.widget.ListAdapter import android.widget.ListView object ListHelper { fun getListViewSize(myListView: ListView) { val myListAdapter: ListAdapter = myListView.adapter ?: //do nothing return null return //set listAdapter in loop for getting final size var totalHeight = 0 for (size in 0 until myListAdapter.count) { val listItem = myListAdapter.getView(size, null, myListView) listItem.measure(0, 0) totalHeight += listItem.measuredHeight } //setting listView item in adapter val params = myListView.layoutParams params.height = totalHeight + myListView.dividerHeight * (myListAdapter.count - 1) myListView.layoutParams = params // print height of adapter on log Log.i("height of listItem:", totalHeight.toString()) } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1172, "s": 1062, "text": "This example demonstrates how to put a ListView into a ScrollView without it collapsing on Android in Kotlin." }, { "code": null, "e": 1301, "s": 1172, "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": 1366, "s": 1301, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1939, "s": 1366, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n<LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n<ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" />\n</LinearLayout>\n</ScrollView>" }, { "code": null, "e": 1994, "s": 1939, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2764, "s": 1994, "text": "import android.os.Bundle\nimport android.widget.ArrayAdapter\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private val listViewArray = arrayOf(\n \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\",\n \"TEN\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\"\n )\n lateinit var list: ListView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\";\n list = findViewById(R.id.listView)\n list.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listViewArray)\n ListHelper.getListViewSize(list)\n }\n}" }, { "code": null, "e": 2840, "s": 2764, "text": "Step 4 − Create a new Kotlin class ListHelper.kt and add the following code" }, { "code": null, "e": 3714, "s": 2840, "text": "import android.util.Log\nimport android.widget.ListAdapter\nimport android.widget.ListView\nobject ListHelper {\n fun getListViewSize(myListView: ListView) {\n val myListAdapter: ListAdapter = myListView.adapter\n ?: //do nothing return null\n return\n //set listAdapter in loop for getting final size\n var totalHeight = 0\n for (size in 0 until myListAdapter.count) {\n val listItem = myListAdapter.getView(size, null, myListView)\n listItem.measure(0, 0)\n totalHeight += listItem.measuredHeight\n }\n //setting listView item in adapter\n val params = myListView.layoutParams\n params.height =\n totalHeight + myListView.dividerHeight * (myListAdapter.count - 1)\n myListView.layoutParams = params\n // print height of adapter on log\n Log.i(\"height of listItem:\", totalHeight.toString())\n }\n}" }, { "code": null, "e": 3769, "s": 3714, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4440, "s": 3769, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4788, "s": 4440, "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" } ]
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks
16 Nov, 2020 Given the following statements: S1: A foreign key declaration can always be replaced by an equivalent check assertion in SQL. S2: Given the table R(a,b,c) where a and b together form the primary key, the following is a valid table definition. CREATE TABLE S ( a INTEGER, d INTEGER, e INTEGER, PRIMARY KEY (d), FOREIGN KEY (a) references R) Which one of the following statements is CORRECT?(A) S1 is TRUE and S2 is FALSE.(B) Both S1 and S2 are TRUE.(C) S1 is FALSE and S2 is TRUE.(D) Both S1 and S2 are FALSE.Answer: (D)Explanation: Check assertions are not sufficient to replace foreign key. Foreign key declaration may have cascade delete which is not possible by just check insertion. Using a check condition we can have the same effect as Foreign key while adding elements to the child table. But when we delete an element from the parent table the referential integrity constraint is no longer valid. So, a check constraint cannot replace a foreign key. So, we cannot replace it with a single check. S2: Given the table R(a,b,c) where a and b together form the primary key, the following is a valid table definition. CREATE TABLE S ( a INTEGER, d INTEGER, e INTEGER, PRIMARY KEY (d), FOREIGN KEY (a) references R) False: Foreign key in one table should uniquely identifies a row of other table. In above table definition, table S has a foreign key that refers to field ‘a’ of R. The field ‘a’ in table S doesn’t uniquely identify a row in table R.Quiz of this Question sk200112 GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(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-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24466, "s": 24438, "text": "\n16 Nov, 2020" }, { "code": null, "e": 24498, "s": 24466, "text": "Given the following statements:" }, { "code": null, "e": 24917, "s": 24498, "text": " S1: A foreign key declaration can always \n be replaced by an equivalent check\n assertion in SQL.\n S2: Given the table R(a,b,c) where a and\n b together form the primary key, the \n following is a valid table definition.\n CREATE TABLE S (\n a INTEGER,\n d INTEGER,\n e INTEGER,\n PRIMARY KEY (d),\n FOREIGN KEY (a) references R) " }, { "code": null, "e": 25265, "s": 24917, "text": "Which one of the following statements is CORRECT?(A) S1 is TRUE and S2 is FALSE.(B) Both S1 and S2 are TRUE.(C) S1 is FALSE and S2 is TRUE.(D) Both S1 and S2 are FALSE.Answer: (D)Explanation: Check assertions are not sufficient to replace foreign key. Foreign key declaration may have cascade delete which is not possible by just check insertion. " }, { "code": null, "e": 25536, "s": 25265, "text": "Using a check condition we can have the same effect as Foreign key while adding elements to the child table. But when we delete an element from the parent table the referential integrity constraint is no longer valid. So, a check constraint cannot replace a foreign key." }, { "code": null, "e": 25582, "s": 25536, "text": "So, we cannot replace it with a single check." }, { "code": null, "e": 25890, "s": 25584, "text": " S2: Given the table R(a,b,c) where a and\n b together form the primary key, the\n following is a valid table definition.\n CREATE TABLE S (\n a INTEGER,\n d INTEGER,\n e INTEGER,\n PRIMARY KEY (d),\n FOREIGN KEY (a) references R) \n\n\n" }, { "code": null, "e": 26145, "s": 25890, "text": "False: Foreign key in one table should uniquely identifies a row of other table. In above table definition, table S has a foreign key that refers to field ‘a’ of R. The field ‘a’ in table S doesn’t uniquely identify a row in table R.Quiz of this Question" }, { "code": null, "e": 26154, "s": 26145, "text": "sk200112" }, { "code": null, "e": 26175, "s": 26154, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26201, "s": 26175, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 26206, "s": 26201, "text": "GATE" }, { "code": null, "e": 26304, "s": 26206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26313, "s": 26304, "text": "Comments" }, { "code": null, "e": 26326, "s": 26313, "text": "Old Comments" }, { "code": null, "e": 26360, "s": 26326, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 26393, "s": 26360, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 26435, "s": 26393, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26477, "s": 26435, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26511, "s": 26477, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26553, "s": 26511, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26587, "s": 26553, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26629, "s": 26587, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26671, "s": 26629, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" } ]
Implementing XGBoost from scratch | by Siddhesh Jadhav | Towards Data Science
XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It has been used in almost every machine learning hackathon and is usually the first preference while choosing a model. But understanding how it actually works is always the difficult part. The complex math was quite difficult to understand at first so I decided to write the code for XGBoost using Numpy. This would help understand it in easy way. This is a different approach of understanding XGBoost through scratch code.The following code is a simple XGBoost model developed using numpy. Tha main purpose of this code is to unveil the maths behind XGBoost. import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline Numpy — To implement the math behind xgboostPandas — To convert list values into dataframeMatplotlib — To plot the final output to visualize the result Sample data : Consider the following data where the years of experience is predictor variable and salary is the target. year = [5,7,12,23,25,28,29,34,35,40]salary = [82,80,103,118,172,127,204,189,99,166] Using regression trees as base learners, we can create a model to predict the salary. For the sake of simplicity, we can choose square loss as our loss function and our objective would be to minimize the square error. As the first step, the model should be initialized with a function F0(x). F0(x) should be a function which minimizes the loss function or MSE (mean squared error) For MSE the Function F minimizes at mean If we had taken MAE , the function would have minimized at median Data building df = pd.DataFrame(columns=['Years','Salary'])df.Years = yeardf.Salary = salarydf.head() The residual is the difference between y and f0 i.e. (y-f0) We can use the residuals from F0(x) to create h1(x). h1(x) will be a regression tree which will try and reduce the residuals from the previous step. The output of h1(x) won’t be a prediction of y; instead, it will help in predicting the successive function F1(x) which will bring down the residuals. The additive model h1(x) computes the mean of the residuals (y — F0) at each leaf of the tree. A split is done and the mean of upper part and lower part is calculated Here , I have selected a random split point. Model building : for i in range(2): f = df.Salary.mean() if(i>0): df['f'+str(i)] = df['f'+str(i-1)] + df['h'+str(i)] else: df['f'+str(i)] = f df['y-f'+str(i)] = df.Salary - df['f'+str(i)] splitIndex = np.random.randint(0,df.shape[0]-1) a= [] h_upper = df['y-f'+str(i)][0:splitIndex].mean() h_bottom = df['y-f'+str(i)][splitIndex:].mean() for j in range(splitIndex): a.append(h_upper) for j in range(df.shape[0]-splitIndex): a.append(h_bottom) df['h'+str(i+1)] = a df.head() If we continue to iterate for 100 times , we can see the Loss of MSE(Fi) decreasing by a huge margin for i in range(100): f = df.Salary.mean() if(i>0): df['f'+str(i)] = df['f'+str(i-1)] + df['h'+str(i)] else: df['f'+str(i)] = f df['y-f'+str(i)] = df.Salary - df['f'+str(i)] splitIndex = np.random.randint(0,df.shape[0]-1) a= [] h_upper = df['y-f'+str(i)][0:splitIndex].mean() h_bottom = df['y-f'+str(i)][splitIndex:].mean() for j in range(splitIndex): a.append(h_upper) for j in range(df.shape[0]-splitIndex): a.append(h_bottom) df['h'+str(i+1)] = a df.head() We can see the loss decreasing and the model adapting to the dataset as the iteration increases plt.figure(figsize=(15,10))plt.scatter(df.Years,df.Salary)plt.plot(df.Years,df.f1,label = 'f1')plt.plot(df.Years,df.f10,label = 'f10')plt.plot(df.Years,df.f99,label = 'f99')plt.legend() The blue line represents output after 1 iterations which can be interpreted as random. As we reach the 100th iteration, the model adapts to the data and loss decreases thus making the output close to the actual points. The code can be found on my github repo : https://github.com/Sid11/XGBoost-Using-Numpy/ Hope you like it !
[ { "code": null, "e": 289, "s": 171, "text": "XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable." }, { "code": null, "e": 409, "s": 289, "text": "It has been used in almost every machine learning hackathon and is usually the first preference while choosing a model." }, { "code": null, "e": 638, "s": 409, "text": "But understanding how it actually works is always the difficult part. The complex math was quite difficult to understand at first so I decided to write the code for XGBoost using Numpy. This would help understand it in easy way." }, { "code": null, "e": 850, "s": 638, "text": "This is a different approach of understanding XGBoost through scratch code.The following code is a simple XGBoost model developed using numpy. Tha main purpose of this code is to unveil the maths behind XGBoost." }, { "code": null, "e": 937, "s": 850, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 1089, "s": 937, "text": "Numpy — To implement the math behind xgboostPandas — To convert list values into dataframeMatplotlib — To plot the final output to visualize the result" }, { "code": null, "e": 1103, "s": 1089, "text": "Sample data :" }, { "code": null, "e": 1209, "s": 1103, "text": "Consider the following data where the years of experience is predictor variable and salary is the target." }, { "code": null, "e": 1293, "s": 1209, "text": "year = [5,7,12,23,25,28,29,34,35,40]salary = [82,80,103,118,172,127,204,189,99,166]" }, { "code": null, "e": 1379, "s": 1293, "text": "Using regression trees as base learners, we can create a model to predict the salary." }, { "code": null, "e": 1511, "s": 1379, "text": "For the sake of simplicity, we can choose square loss as our loss function and our objective would be to minimize the square error." }, { "code": null, "e": 1715, "s": 1511, "text": "As the first step, the model should be initialized with a function F0(x). F0(x) should be a function which minimizes the loss function or MSE (mean squared error) For MSE the Function F minimizes at mean" }, { "code": null, "e": 1781, "s": 1715, "text": "If we had taken MAE , the function would have minimized at median" }, { "code": null, "e": 1795, "s": 1781, "text": "Data building" }, { "code": null, "e": 1883, "s": 1795, "text": "df = pd.DataFrame(columns=['Years','Salary'])df.Years = yeardf.Salary = salarydf.head()" }, { "code": null, "e": 1943, "s": 1883, "text": "The residual is the difference between y and f0 i.e. (y-f0)" }, { "code": null, "e": 2243, "s": 1943, "text": "We can use the residuals from F0(x) to create h1(x). h1(x) will be a regression tree which will try and reduce the residuals from the previous step. The output of h1(x) won’t be a prediction of y; instead, it will help in predicting the successive function F1(x) which will bring down the residuals." }, { "code": null, "e": 2338, "s": 2243, "text": "The additive model h1(x) computes the mean of the residuals (y — F0) at each leaf of the tree." }, { "code": null, "e": 2455, "s": 2338, "text": "A split is done and the mean of upper part and lower part is calculated Here , I have selected a random split point." }, { "code": null, "e": 2472, "s": 2455, "text": "Model building :" }, { "code": null, "e": 2993, "s": 2472, "text": "for i in range(2): f = df.Salary.mean() if(i>0): df['f'+str(i)] = df['f'+str(i-1)] + df['h'+str(i)] else: df['f'+str(i)] = f df['y-f'+str(i)] = df.Salary - df['f'+str(i)] splitIndex = np.random.randint(0,df.shape[0]-1) a= [] h_upper = df['y-f'+str(i)][0:splitIndex].mean() h_bottom = df['y-f'+str(i)][splitIndex:].mean() for j in range(splitIndex): a.append(h_upper) for j in range(df.shape[0]-splitIndex): a.append(h_bottom) df['h'+str(i+1)] = a df.head()" }, { "code": null, "e": 3094, "s": 2993, "text": "If we continue to iterate for 100 times , we can see the Loss of MSE(Fi) decreasing by a huge margin" }, { "code": null, "e": 3617, "s": 3094, "text": "for i in range(100): f = df.Salary.mean() if(i>0): df['f'+str(i)] = df['f'+str(i-1)] + df['h'+str(i)] else: df['f'+str(i)] = f df['y-f'+str(i)] = df.Salary - df['f'+str(i)] splitIndex = np.random.randint(0,df.shape[0]-1) a= [] h_upper = df['y-f'+str(i)][0:splitIndex].mean() h_bottom = df['y-f'+str(i)][splitIndex:].mean() for j in range(splitIndex): a.append(h_upper) for j in range(df.shape[0]-splitIndex): a.append(h_bottom) df['h'+str(i+1)] = a df.head()" }, { "code": null, "e": 3713, "s": 3617, "text": "We can see the loss decreasing and the model adapting to the dataset as the iteration increases" }, { "code": null, "e": 3899, "s": 3713, "text": "plt.figure(figsize=(15,10))plt.scatter(df.Years,df.Salary)plt.plot(df.Years,df.f1,label = 'f1')plt.plot(df.Years,df.f10,label = 'f10')plt.plot(df.Years,df.f99,label = 'f99')plt.legend()" }, { "code": null, "e": 4118, "s": 3899, "text": "The blue line represents output after 1 iterations which can be interpreted as random. As we reach the 100th iteration, the model adapts to the data and loss decreases thus making the output close to the actual points." }, { "code": null, "e": 4206, "s": 4118, "text": "The code can be found on my github repo : https://github.com/Sid11/XGBoost-Using-Numpy/" } ]
Wrap a page's content with Bootstrap
To wrap a page's content, use the .container class, <div class = "container"> ... </div> The following is the .container class in bootstrap.css file: .container{ padding-right: 20px; padding-left: 20px; margin-right: auto; margin-left: auto; }
[ { "code": null, "e": 1115, "s": 1062, "text": "To wrap a page's content, use the .container class, " }, { "code": null, "e": 1152, "s": 1115, "text": "<div class = \"container\">\n...\n</div>" }, { "code": null, "e": 1214, "s": 1152, "text": "The following is the .container class in bootstrap.css file: " }, { "code": null, "e": 1324, "s": 1214, "text": ".container{\n padding-right: 20px;\n padding-left: 20px;\n margin-right: auto;\n margin-left: auto;\n}" } ]
How to load and display an image in ImageView on Android App?
This example demonstrates how to load and display an image in ImageView on Android App. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context=".MyAndroidAppActivity"> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btnChangeImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Image" /> </LinearLayout> Step 3 − Add the following code to src/MyAndroidAppActivity.java package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.view.View; import android.view.View.OnClickListener; public class MyAndroidAppActivity extends AppCompatActivity { Button button; ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenerOnButton(); } public void addListenerOnButton() { image=(ImageView) findViewById(R.id.imageView1); button=(Button) findViewById(R.id.btnChangeImage); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { image.setImageResource(R.drawable.ic_launcher_background); } }); } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample"> <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=".MyAndroidAppActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1150, "s": 1062, "text": "This example demonstrates how to load and display an image in ImageView on Android App." }, { "code": null, "e": 1279, "s": 1150, "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": 1344, "s": 1279, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2035, "s": 1344, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MyAndroidAppActivity\">\n <ImageView\n android:id=\"@+id/imageView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"/>\n <Button\n android:id=\"@+id/btnChangeImage\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Change Image\" />\n</LinearLayout>" }, { "code": null, "e": 2100, "s": 2035, "text": "Step 3 − Add the following code to src/MyAndroidAppActivity.java" }, { "code": null, "e": 3021, "s": 2100, "text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.view.View;\nimport android.view.View.OnClickListener;\npublic class MyAndroidAppActivity extends AppCompatActivity {\n Button button;\n ImageView image;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n addListenerOnButton();\n }\n public void addListenerOnButton() {\n image=(ImageView) findViewById(R.id.imageView1);\n button=(Button) findViewById(R.id.btnChangeImage);\n button.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View arg0) {\n image.setImageResource(R.drawable.ic_launcher_background);\n }\n });\n }\n}" }, { "code": null, "e": 3086, "s": 3021, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3768, "s": 3086, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.sample\">\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=\".MyAndroidAppActivity\">\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": 4116, "s": 3768, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4156, "s": 4116, "text": "Click here to download the project code" } ]
Adam Number | Practice | GeeksforGeeks
Given a number N, write a program to check whether given number is Adam Number or not. Adam number is a number when reversed, the square of the number and the square of the reversed number should be numbers which are reverse of each other. Example 1: Input: N = 12 Output: YES Explanation: 122 = 144 and 212 = 441. 144 reversed gives 441, So, it's an Adam Number. Example 1: Input: N = 14 Output: NO Explanation: 142 = 196. 196 reversed gives 691, which isn't equal to 412 So, it's not an Adam Number. Your Task: You don't need to read input or print anything. Your task is to complete the function checkAdamOrNot() which takes an Integer N as input and returns the answer as "YES" if it is a Adam, number. Otherwise, returns "NO". Expected Time Complexity: O(|N|) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 104 0 badgujarsachin833 months ago string checkAdamOrNot(int N) { // code here long long int a=N*N; int reverse=0; int temp=N; while(temp>0){ reverse=reverse*10+(temp%10); temp/=10; } long long int ans=reverse*reverse; long long int ok=0; while(ans>0){ ok=ok*10+(ans%10); ans/=10; } if(ok==a){ return "YES"; }else{ return "NO"; } } +1 rdm1233 months ago def checkAdamOrNot(self, N): a=N*N s=str(N)[::-1] b=int(s)*int(s) if(str(a)==str(b)[::-1]): return "YES" return "NO" 0 SACHIN KUMAR1 year ago SACHIN KUMAR public: string checkAdamOrNot(int N) { long long int sq = N*N; int temp = N; int reverse = 0 ; while(temp) { int r = temp % 10; reverse = (reverse * 10) + r; temp /= 10; } long long int r_sq = reverse*reverse; long long int sq_reverse = 0; while(r_sq) { int r = r_sq % 10; sq_reverse = (sq_reverse * 10) + r; r_sq /= 10; } if(sq == sq_reverse) { return "YES"; } else { return "NO"; } } 0 Sreedhar Karanam2 years ago Sreedhar Karanam Python solution (0.07 sec):class Solution: def checkAdamOrNot(self, N): # code here if(str(N**2)==str(int(str(N)[::-1])**2)[::-1]): return "YES" else: return "NO" 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": 478, "s": 238, "text": "Given a number N, write a program to check whether given number is Adam Number or not.\nAdam number is a number when reversed, the square of the number and the square of the reversed number should be numbers which are reverse of each other." }, { "code": null, "e": 492, "s": 480, "text": "Example 1: " }, { "code": null, "e": 607, "s": 492, "text": "Input: \nN = 12\nOutput:\nYES\nExplanation:\n122 = 144 and 212 = 441. 144 reversed \ngives 441, So, it's an Adam Number." }, { "code": null, "e": 619, "s": 607, "text": "Example 1: " }, { "code": null, "e": 747, "s": 619, "text": "Input: \nN = 14\nOutput:\nNO\nExplanation:\n142 = 196. 196 reversed gives 691,\nwhich isn't equal to 412 So,\nit's not an Adam Number." }, { "code": null, "e": 979, "s": 749, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function checkAdamOrNot() which takes an Integer N as input and returns the answer as \"YES\" if it is a Adam, number. Otherwise, returns \"NO\"." }, { "code": null, "e": 1045, "s": 981, "text": "Expected Time Complexity: O(|N|)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1074, "s": 1047, "text": "Constraints:\n1 <= N <= 104" }, { "code": null, "e": 1076, "s": 1074, "text": "0" }, { "code": null, "e": 1105, "s": 1076, "text": "badgujarsachin833 months ago" }, { "code": null, "e": 1592, "s": 1105, "text": " string checkAdamOrNot(int N) {\n // code here\n long long int a=N*N;\n int reverse=0;\n int temp=N;\n while(temp>0){\n reverse=reverse*10+(temp%10);\n temp/=10;\n }\n long long int ans=reverse*reverse;\n long long int ok=0;\n while(ans>0){\n ok=ok*10+(ans%10);\n ans/=10;\n }\n if(ok==a){\n return \"YES\";\n }else{\n return \"NO\";\n }\n \n }" }, { "code": null, "e": 1595, "s": 1592, "text": "+1" }, { "code": null, "e": 1614, "s": 1595, "text": "rdm1233 months ago" }, { "code": null, "e": 1783, "s": 1614, "text": "def checkAdamOrNot(self, N):\n a=N*N\n s=str(N)[::-1]\n b=int(s)*int(s)\n if(str(a)==str(b)[::-1]):\n return \"YES\"\n return \"NO\"" }, { "code": null, "e": 1785, "s": 1783, "text": "0" }, { "code": null, "e": 1808, "s": 1785, "text": "SACHIN KUMAR1 year ago" }, { "code": null, "e": 1821, "s": 1808, "text": "SACHIN KUMAR" }, { "code": null, "e": 2423, "s": 1821, "text": " public: string checkAdamOrNot(int N) { long long int sq = N*N; int temp = N; int reverse = 0 ; while(temp) { int r = temp % 10; reverse = (reverse * 10) + r; temp /= 10; } long long int r_sq = reverse*reverse; long long int sq_reverse = 0; while(r_sq) { int r = r_sq % 10; sq_reverse = (sq_reverse * 10) + r; r_sq /= 10; } if(sq == sq_reverse) { return \"YES\"; } else { return \"NO\"; } }" }, { "code": null, "e": 2425, "s": 2423, "text": "0" }, { "code": null, "e": 2453, "s": 2425, "text": "Sreedhar Karanam2 years ago" }, { "code": null, "e": 2470, "s": 2453, "text": "Sreedhar Karanam" }, { "code": null, "e": 2680, "s": 2470, "text": "Python solution (0.07 sec):class Solution: def checkAdamOrNot(self, N): # code here if(str(N**2)==str(int(str(N)[::-1])**2)[::-1]): return \"YES\" else: return \"NO\"" }, { "code": null, "e": 2826, "s": 2680, "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": 2862, "s": 2826, "text": " Login to access your submissions. " }, { "code": null, "e": 2872, "s": 2862, "text": "\nProblem\n" }, { "code": null, "e": 2882, "s": 2872, "text": "\nContest\n" }, { "code": null, "e": 2945, "s": 2882, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3093, "s": 2945, "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": 3301, "s": 3093, "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": 3407, "s": 3301, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Creating scrollable Listbox within a grid using Tkinter
A Listbox widget displays a list of items such as numbers list, items list, list of employees in a company, etc. There might be a case when a long list of items in a Listbox needs a way to be viewed inside the window. For this purpose, we can attach scrollbars to the Listbox widget by initializing the Scrollbar() object. If we configure and attach the Listbox with the scrollbar, it will make the Listbox scrollable. In this example, we will create a Listbox with a list of numbers ranging from 1 to 100. The Listbox widget has an associated Scrollbar with it. #Import the required libraries from tkinter import * from tkinter import ttk #Create an instance of Tkinter Frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("700x350") #Create an object of Scrollbar widget s = Scrollbar() #Create a horizontal scrollbar scrollbar = ttk.Scrollbar(win, orient= 'vertical') scrollbar.pack(side= RIGHT, fill= BOTH) #Add a Listbox Widget listbox = Listbox(win, width= 350, font= ('Helvetica 15 bold')) listbox.pack(side= LEFT, fill= BOTH) #Add values to the Listbox for values in range(1,101): listbox.insert(END, values) listbox.config(yscrollcommand= scrollbar.set) #Configure the scrollbar scrollbar.config(command= listbox.yview) win.mainloop() Running the above code will display a window containing a scrollable Listbox.
[ { "code": null, "e": 1481, "s": 1062, "text": "A Listbox widget displays a list of items such as numbers list, items list, list of employees in a company, etc. There might be a case when a long list of items in a Listbox needs a way to be viewed inside the window. For this purpose, we can attach scrollbars to the Listbox widget by initializing the Scrollbar() object. If we configure and attach the Listbox with the scrollbar, it will make the Listbox scrollable." }, { "code": null, "e": 1625, "s": 1481, "text": "In this example, we will create a Listbox with a list of numbers ranging from 1 to 100. The Listbox widget has an associated Scrollbar with it." }, { "code": null, "e": 2330, "s": 1625, "text": "#Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry of Tkinter Frame\nwin.geometry(\"700x350\")\n\n#Create an object of Scrollbar widget\ns = Scrollbar()\n\n#Create a horizontal scrollbar\nscrollbar = ttk.Scrollbar(win, orient= 'vertical')\nscrollbar.pack(side= RIGHT, fill= BOTH)\n\n#Add a Listbox Widget\nlistbox = Listbox(win, width= 350, font= ('Helvetica 15 bold'))\nlistbox.pack(side= LEFT, fill= BOTH)\n\n#Add values to the Listbox\nfor values in range(1,101):\n listbox.insert(END, values)\n\nlistbox.config(yscrollcommand= scrollbar.set)\n\n#Configure the scrollbar\nscrollbar.config(command= listbox.yview)\n\nwin.mainloop()" }, { "code": null, "e": 2408, "s": 2330, "text": "Running the above code will display a window containing a scrollable Listbox." } ]
Building Blocks: Text Pre-Processing | by Shashank Kapadia | Towards Data Science
In the last article of our series, we introduced the concept of Natural Language Processing, you can read it here, and now you probably want to try it yourself, right? Great! Without further ado, let’s dive in to the building blocks for statistical natural language processing. In this article, we’ll introduce the key concepts, along with practical implementation in Python and the challenges to keep in mind at the time of application. The complete code is available as a Jupyter Notebook on GitHub. Normalizing the text means converting it to a more convenient, standard form before performing turning it to features for higher level modeling. Think of this step as converting human readable language into a form that is machine readable. The standard framework to normalize the text includes: TokenizationStop Words RemovalMorphological NormalizationCollocation Tokenization Stop Words Removal Morphological Normalization Collocation Data preprocessing consists of a number of steps, any number of which may or not apply to a given task. More generally, in this article we’ll discuss some predetermined body of text, and perform some basic transformative analysis that can be used for performing further, more meaningful natural language processing [1] Given a character sequence and a defined document unit (blurb of texts), tokenization is the task of chopping it up into pieces, called tokens, perhaps at the same time throwing away certain characters/words, such as punctuation [2]. Ordinarily, there are two types of tokenization: Word Tokenization: Used to separate words via unique space character. Depending on the application, word tokenization may also tokenize multi-word expressions like New York. This is often times is closely tied to a process called Named Entity Recognition. Later in this tutorial, we will look at Collocation (Phrase) Modeling that helps address part of this challengeSentence Tokenization/Segmentation: Along with word tokenization, sentence segmentation is a crucial step in text processing. This is usually performed based on punctuations such as “.”, “?”, “!” as they tend to mark the sentence boundaries Word Tokenization: Used to separate words via unique space character. Depending on the application, word tokenization may also tokenize multi-word expressions like New York. This is often times is closely tied to a process called Named Entity Recognition. Later in this tutorial, we will look at Collocation (Phrase) Modeling that helps address part of this challenge Sentence Tokenization/Segmentation: Along with word tokenization, sentence segmentation is a crucial step in text processing. This is usually performed based on punctuations such as “.”, “?”, “!” as they tend to mark the sentence boundaries Challenges: The use of abbreviations can prompt the tokenizer to detect a sentence boundary where there is none. Numbers, special characters, hyphenation, and capitalization. In the expressions “don’t,” “I’d,” “John’s” do we have one, two or three tokens? Implementation example: from nltk.tokenize import sent_tokenize, word_tokenize#Sentence Tokenizationprint ('Following is the list of sentences tokenized from the sample review\n')sample_text = """The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving"""tokenize_sentence = sent_tokenize(sample_text)print (tokenize_sentence)print ('---------------------------------------------------------\n')print ('Following is the list of words tokenized from the sample review sentence\n')tokenize_words = word_tokenize(tokenize_sentence[1])print (tokenize_words) Output: Following is the list of sentences tokenized from the sample review['The first time I ate here I honestly was not that impressed.', 'I decided to wait a bit and give it another chance.', 'I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and \nswiss burgers I had were honestly very good.', 'The shakes were also tasty.', 'Although Mad Mikes is still my favorite burger around, \nyou can do a heck of a lot worse than Smashburger if you get a craving']---------------------------------------------------------Following is the list of words tokenized from the sample review sentence['I', 'decided', 'to', 'wait', 'a', 'bit', 'and', 'give', 'it', 'another', 'chance', '.'] Often, there are a few ubiquitous words which would appear to be of little value in helping the purpose of analysis but increases the dimensionality of feature set, are excluded from the vocabulary entirely as the part of stop words removal process. There are two considerations usually that motivate this removal. Irrelevance: Allows one to analyze only on content-bearing words. Stopwords, also called empty words because they generally do not bear much meaning, introduce noise in the analysis/modeling processDimension: Removing the stopwords also allows one to reduce the tokens in documents significantly, and thereby decreasing feature dimension Irrelevance: Allows one to analyze only on content-bearing words. Stopwords, also called empty words because they generally do not bear much meaning, introduce noise in the analysis/modeling process Dimension: Removing the stopwords also allows one to reduce the tokens in documents significantly, and thereby decreasing feature dimension Challenges: Converting all characters into lowercase letters before stopwords removal process can introduce ambiguity in the text, and sometimes entirely changing the meaning of it. For example, with the expressions “US citizen” will be viewed as “us citizen” or “IT scientist” as “it scientist”. Since both *us* and *it* are normally considered stop words, it would result in an inaccurate outcome. The strategy regarding the treatment of stopwords can thus be refined by identifying that “US” and “IT” are not pronouns in the above examples, through a part-of-speech tagging step. Implementation example: from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize# define the language for stopwords removalstopwords = set(stopwords.words("english"))print ("""{0} stop words""".format(len(stopwords)))tokenize_words = word_tokenize(sample_text)filtered_sample_text = [w for w in tokenize_words if not w in stopwords]print ('\nOriginal Text:')print ('------------------\n')print (sample_text)print ('\n Filtered Text:')print ('------------------\n')print (' '.join(str(token) for token in filtered_sample_text)) Output: 179 stop wordsOriginal Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving Filtered Text:------------------The first time I ate I honestly impressed . I decided wait bit give another chance . I recently eaten couple times although I convinced pricing particularly point two mushroom swiss burgers I honestly good . The shakes also tasty . Although Mad Mikes still favorite burger around , heck lot worse Smashburger get craving Morphology, in general, is the study of the way words are built up from smaller meaning-bearing units, morphomes. For example, dogs consists of two morphemes: dog and s Two commonly used techniques for text normalization are: Stemming: The procedure aims to identify the stem of a word and use it in lieu of the word itself. The most popular algorithm for stemming English, and one that has repeatedly been shown to be empirically very effective, is Porter’s algorithm. The entire algorithm is too long and intricate to present here [3], but you can find details hereLemmatization: This process refers to doing things correctly with the use of vocabulary and morphological analysis of words, typically aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma. Stemming: The procedure aims to identify the stem of a word and use it in lieu of the word itself. The most popular algorithm for stemming English, and one that has repeatedly been shown to be empirically very effective, is Porter’s algorithm. The entire algorithm is too long and intricate to present here [3], but you can find details here Lemmatization: This process refers to doing things correctly with the use of vocabulary and morphological analysis of words, typically aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma. If confronted with the token saw, stemming might return just s, whereas lemmatization would attempt to return either see or saw depending on whether the use of the token was as a verb or a noun [4] Implementation example: from nltk.stem import PorterStemmerfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizeps = PorterStemmer()lemmatizer = WordNetLemmatizer()tokenize_words = word_tokenize(sample_text)stemmed_sample_text = []for token in tokenize_words: stemmed_sample_text.append(ps.stem(token))lemma_sample_text = []for token in tokenize_words: lemma_sample_text.append(lemmatizer.lemmatize(token)) print ('\nOriginal Text:')print ('------------------\n')print (sample_text)print ('\nFiltered Text: Stemming')print ('------------------\n')print (' '.join(str(token) for token in stemmed_sample_text))print ('\nFiltered Text: Lemmatization')print ('--------------------------------\n')print (' '.join(str(token) for token in lemma_sample_text)) Output: Original Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving.Filtered Text: Stemming:------------------the first time I ate here I honestli wa not that impress . I decid to wait a bit and give it anoth chanc . I have recent eaten there a coupl of time and although I am not convinc that the price is particularli on point the two mushroom and swiss burger I had were honestli veri good . the shake were also tasti . although mad mike is still my favorit burger around , you can do a heck of a lot wors than smashburg if you get a crave .Filtered Text: Lemmatization--------------------------------The first time I ate here I honestly wa not that impressed . I decided to wait a bit and give it another chance . I have recently eaten there a couple of time and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burger I had were honestly very good . The shake were also tasty . Although Mad Mikes is still my favorite burger around , you can do a heck of a lot worse than Smashburger if you get a craving . Challenges: Often, full morphological analysis produces at most very modest benefits for analysis. Neither form of normalization improve language information performance in aggregate, both from relevance and dimensionality reduction standpoint — at least not for the following situations: Implementation example: from nltk.stem import PorterStemmerwords = ["operate", "operating", "operates", "operation", "operative", "operatives", "operational"]ps = PorterStemmer()for token in words: print (ps.stem(token)) Output: operoperoperoperoperoperoper As an example of what can go wrong, note that the Porter stemmer stems all of the following words to oper However, since operate in its various forms is a common verb, we would expect to lose considerable precision [4]: operational AND research operating AND system operative AND dentistry For cases like these, moving to using a lemmatizer would not completely fix the problem because particular inflectional forms are used in specific collocations. Getting better value from term normalization depends more on pragmatic issues of word use than on formal issues of linguistic morphology [4] For all the codes used to generate above results, click here. And that’s it! Now you know all about gradient descent, linear regression, and logistic regression.” In the next article, we’ll discuss in detail the concept of collocation (phrase) modeling, and walkthrough together its implementation. Stay tuned and keep learning! [1] A General Approach to Preprocessing Text Data — KDnuggets. https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html [2] Tokenization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html [3] Text Mining in Bovine Diseases — ijcaonline.org. https://www.ijcaonline.org/volume6/number10/pxc3871454.pdf [4] Stemming and lemmatization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html If you have any feedback, please reach out by commenting on this post, messaging me on LinkedIn, or shooting me an email (shmkapadia[at]gmail.com)
[ { "code": null, "e": 449, "s": 171, "text": "In the last article of our series, we introduced the concept of Natural Language Processing, you can read it here, and now you probably want to try it yourself, right? Great! Without further ado, let’s dive in to the building blocks for statistical natural language processing." }, { "code": null, "e": 673, "s": 449, "text": "In this article, we’ll introduce the key concepts, along with practical implementation in Python and the challenges to keep in mind at the time of application. The complete code is available as a Jupyter Notebook on GitHub." }, { "code": null, "e": 913, "s": 673, "text": "Normalizing the text means converting it to a more convenient, standard form before performing turning it to features for higher level modeling. Think of this step as converting human readable language into a form that is machine readable." }, { "code": null, "e": 968, "s": 913, "text": "The standard framework to normalize the text includes:" }, { "code": null, "e": 1037, "s": 968, "text": "TokenizationStop Words RemovalMorphological NormalizationCollocation" }, { "code": null, "e": 1050, "s": 1037, "text": "Tokenization" }, { "code": null, "e": 1069, "s": 1050, "text": "Stop Words Removal" }, { "code": null, "e": 1097, "s": 1069, "text": "Morphological Normalization" }, { "code": null, "e": 1109, "s": 1097, "text": "Collocation" }, { "code": null, "e": 1428, "s": 1109, "text": "Data preprocessing consists of a number of steps, any number of which may or not apply to a given task. More generally, in this article we’ll discuss some predetermined body of text, and perform some basic transformative analysis that can be used for performing further, more meaningful natural language processing [1]" }, { "code": null, "e": 1711, "s": 1428, "text": "Given a character sequence and a defined document unit (blurb of texts), tokenization is the task of chopping it up into pieces, called tokens, perhaps at the same time throwing away certain characters/words, such as punctuation [2]. Ordinarily, there are two types of tokenization:" }, { "code": null, "e": 2319, "s": 1711, "text": "Word Tokenization: Used to separate words via unique space character. Depending on the application, word tokenization may also tokenize multi-word expressions like New York. This is often times is closely tied to a process called Named Entity Recognition. Later in this tutorial, we will look at Collocation (Phrase) Modeling that helps address part of this challengeSentence Tokenization/Segmentation: Along with word tokenization, sentence segmentation is a crucial step in text processing. This is usually performed based on punctuations such as “.”, “?”, “!” as they tend to mark the sentence boundaries" }, { "code": null, "e": 2687, "s": 2319, "text": "Word Tokenization: Used to separate words via unique space character. Depending on the application, word tokenization may also tokenize multi-word expressions like New York. This is often times is closely tied to a process called Named Entity Recognition. Later in this tutorial, we will look at Collocation (Phrase) Modeling that helps address part of this challenge" }, { "code": null, "e": 2928, "s": 2687, "text": "Sentence Tokenization/Segmentation: Along with word tokenization, sentence segmentation is a crucial step in text processing. This is usually performed based on punctuations such as “.”, “?”, “!” as they tend to mark the sentence boundaries" }, { "code": null, "e": 2940, "s": 2928, "text": "Challenges:" }, { "code": null, "e": 3041, "s": 2940, "text": "The use of abbreviations can prompt the tokenizer to detect a sentence boundary where there is none." }, { "code": null, "e": 3184, "s": 3041, "text": "Numbers, special characters, hyphenation, and capitalization. In the expressions “don’t,” “I’d,” “John’s” do we have one, two or three tokens?" }, { "code": null, "e": 3208, "s": 3184, "text": "Implementation example:" }, { "code": null, "e": 4134, "s": 3208, "text": "from nltk.tokenize import sent_tokenize, word_tokenize#Sentence Tokenizationprint ('Following is the list of sentences tokenized from the sample review\\n')sample_text = \"\"\"The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving\"\"\"tokenize_sentence = sent_tokenize(sample_text)print (tokenize_sentence)print ('---------------------------------------------------------\\n')print ('Following is the list of words tokenized from the sample review sentence\\n')tokenize_words = word_tokenize(tokenize_sentence[1])print (tokenize_words)" }, { "code": null, "e": 4142, "s": 4134, "text": "Output:" }, { "code": null, "e": 4900, "s": 4142, "text": "Following is the list of sentences tokenized from the sample review['The first time I ate here I honestly was not that impressed.', 'I decided to wait a bit and give it another chance.', 'I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and \\nswiss burgers I had were honestly very good.', 'The shakes were also tasty.', 'Although Mad Mikes is still my favorite burger around, \\nyou can do a heck of a lot worse than Smashburger if you get a craving']---------------------------------------------------------Following is the list of words tokenized from the sample review sentence['I', 'decided', 'to', 'wait', 'a', 'bit', 'and', 'give', 'it', 'another', 'chance', '.']" }, { "code": null, "e": 5215, "s": 4900, "text": "Often, there are a few ubiquitous words which would appear to be of little value in helping the purpose of analysis but increases the dimensionality of feature set, are excluded from the vocabulary entirely as the part of stop words removal process. There are two considerations usually that motivate this removal." }, { "code": null, "e": 5553, "s": 5215, "text": "Irrelevance: Allows one to analyze only on content-bearing words. Stopwords, also called empty words because they generally do not bear much meaning, introduce noise in the analysis/modeling processDimension: Removing the stopwords also allows one to reduce the tokens in documents significantly, and thereby decreasing feature dimension" }, { "code": null, "e": 5752, "s": 5553, "text": "Irrelevance: Allows one to analyze only on content-bearing words. Stopwords, also called empty words because they generally do not bear much meaning, introduce noise in the analysis/modeling process" }, { "code": null, "e": 5892, "s": 5752, "text": "Dimension: Removing the stopwords also allows one to reduce the tokens in documents significantly, and thereby decreasing feature dimension" }, { "code": null, "e": 5904, "s": 5892, "text": "Challenges:" }, { "code": null, "e": 6475, "s": 5904, "text": "Converting all characters into lowercase letters before stopwords removal process can introduce ambiguity in the text, and sometimes entirely changing the meaning of it. For example, with the expressions “US citizen” will be viewed as “us citizen” or “IT scientist” as “it scientist”. Since both *us* and *it* are normally considered stop words, it would result in an inaccurate outcome. The strategy regarding the treatment of stopwords can thus be refined by identifying that “US” and “IT” are not pronouns in the above examples, through a part-of-speech tagging step." }, { "code": null, "e": 6499, "s": 6475, "text": "Implementation example:" }, { "code": null, "e": 7018, "s": 6499, "text": "from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize# define the language for stopwords removalstopwords = set(stopwords.words(\"english\"))print (\"\"\"{0} stop words\"\"\".format(len(stopwords)))tokenize_words = word_tokenize(sample_text)filtered_sample_text = [w for w in tokenize_words if not w in stopwords]print ('\\nOriginal Text:')print ('------------------\\n')print (sample_text)print ('\\n Filtered Text:')print ('------------------\\n')print (' '.join(str(token) for token in filtered_sample_text))" }, { "code": null, "e": 7026, "s": 7018, "text": "Output:" }, { "code": null, "e": 7878, "s": 7026, "text": "179 stop wordsOriginal Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving Filtered Text:------------------The first time I ate I honestly impressed . I decided wait bit give another chance . I recently eaten couple times although I convinced pricing particularly point two mushroom swiss burgers I honestly good . The shakes also tasty . Although Mad Mikes still favorite burger around , heck lot worse Smashburger get craving" }, { "code": null, "e": 8047, "s": 7878, "text": "Morphology, in general, is the study of the way words are built up from smaller meaning-bearing units, morphomes. For example, dogs consists of two morphemes: dog and s" }, { "code": null, "e": 8104, "s": 8047, "text": "Two commonly used techniques for text normalization are:" }, { "code": null, "e": 8705, "s": 8104, "text": "Stemming: The procedure aims to identify the stem of a word and use it in lieu of the word itself. The most popular algorithm for stemming English, and one that has repeatedly been shown to be empirically very effective, is Porter’s algorithm. The entire algorithm is too long and intricate to present here [3], but you can find details hereLemmatization: This process refers to doing things correctly with the use of vocabulary and morphological analysis of words, typically aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma." }, { "code": null, "e": 9047, "s": 8705, "text": "Stemming: The procedure aims to identify the stem of a word and use it in lieu of the word itself. The most popular algorithm for stemming English, and one that has repeatedly been shown to be empirically very effective, is Porter’s algorithm. The entire algorithm is too long and intricate to present here [3], but you can find details here" }, { "code": null, "e": 9307, "s": 9047, "text": "Lemmatization: This process refers to doing things correctly with the use of vocabulary and morphological analysis of words, typically aiming to remove inflectional endings only and to return the base or dictionary form of a word, which is known as the lemma." }, { "code": null, "e": 9505, "s": 9307, "text": "If confronted with the token saw, stemming might return just s, whereas lemmatization would attempt to return either see or saw depending on whether the use of the token was as a verb or a noun [4]" }, { "code": null, "e": 9529, "s": 9505, "text": "Implementation example:" }, { "code": null, "e": 10291, "s": 9529, "text": "from nltk.stem import PorterStemmerfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import word_tokenizeps = PorterStemmer()lemmatizer = WordNetLemmatizer()tokenize_words = word_tokenize(sample_text)stemmed_sample_text = []for token in tokenize_words: stemmed_sample_text.append(ps.stem(token))lemma_sample_text = []for token in tokenize_words: lemma_sample_text.append(lemmatizer.lemmatize(token)) print ('\\nOriginal Text:')print ('------------------\\n')print (sample_text)print ('\\nFiltered Text: Stemming')print ('------------------\\n')print (' '.join(str(token) for token in stemmed_sample_text))print ('\\nFiltered Text: Lemmatization')print ('--------------------------------\\n')print (' '.join(str(token) for token in lemma_sample_text))" }, { "code": null, "e": 10299, "s": 10291, "text": "Output:" }, { "code": null, "e": 11776, "s": 10299, "text": "Original Text:------------------The first time I ate here I honestly was not that impressed. I decided to wait a bit and give it another chance. I have recently eaten there a couple of times and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burgers I had were honestly very good. The shakes were also tasty. Although Mad Mikes is still my favorite burger around, you can do a heck of a lot worse than Smashburger if you get a craving.Filtered Text: Stemming:------------------the first time I ate here I honestli wa not that impress . I decid to wait a bit and give it anoth chanc . I have recent eaten there a coupl of time and although I am not convinc that the price is particularli on point the two mushroom and swiss burger I had were honestli veri good . the shake were also tasti . although mad mike is still my favorit burger around , you can do a heck of a lot wors than smashburg if you get a crave .Filtered Text: Lemmatization--------------------------------The first time I ate here I honestly wa not that impressed . I decided to wait a bit and give it another chance . I have recently eaten there a couple of time and although I am not convinced that the pricing is particularly on point the two mushroom and swiss burger I had were honestly very good . The shake were also tasty . Although Mad Mikes is still my favorite burger around , you can do a heck of a lot worse than Smashburger if you get a craving ." }, { "code": null, "e": 11788, "s": 11776, "text": "Challenges:" }, { "code": null, "e": 12065, "s": 11788, "text": "Often, full morphological analysis produces at most very modest benefits for analysis. Neither form of normalization improve language information performance in aggregate, both from relevance and dimensionality reduction standpoint — at least not for the following situations:" }, { "code": null, "e": 12089, "s": 12065, "text": "Implementation example:" }, { "code": null, "e": 12289, "s": 12089, "text": "from nltk.stem import PorterStemmerwords = [\"operate\", \"operating\", \"operates\", \"operation\", \"operative\", \"operatives\", \"operational\"]ps = PorterStemmer()for token in words: print (ps.stem(token))" }, { "code": null, "e": 12297, "s": 12289, "text": "Output:" }, { "code": null, "e": 12326, "s": 12297, "text": "operoperoperoperoperoperoper" }, { "code": null, "e": 12432, "s": 12326, "text": "As an example of what can go wrong, note that the Porter stemmer stems all of the following words to oper" }, { "code": null, "e": 12546, "s": 12432, "text": "However, since operate in its various forms is a common verb, we would expect to lose considerable precision [4]:" }, { "code": null, "e": 12571, "s": 12546, "text": "operational AND research" }, { "code": null, "e": 12592, "s": 12571, "text": "operating AND system" }, { "code": null, "e": 12616, "s": 12592, "text": "operative AND dentistry" }, { "code": null, "e": 12918, "s": 12616, "text": "For cases like these, moving to using a lemmatizer would not completely fix the problem because particular inflectional forms are used in specific collocations. Getting better value from term normalization depends more on pragmatic issues of word use than on formal issues of linguistic morphology [4]" }, { "code": null, "e": 12980, "s": 12918, "text": "For all the codes used to generate above results, click here." }, { "code": null, "e": 13081, "s": 12980, "text": "And that’s it! Now you know all about gradient descent, linear regression, and logistic regression.”" }, { "code": null, "e": 13247, "s": 13081, "text": "In the next article, we’ll discuss in detail the concept of collocation (phrase) modeling, and walkthrough together its implementation. Stay tuned and keep learning!" }, { "code": null, "e": 13390, "s": 13247, "text": "[1] A General Approach to Preprocessing Text Data — KDnuggets. https://www.kdnuggets.com/2017/12/general-approach-preprocessing-text-data.html" }, { "code": null, "e": 13499, "s": 13390, "text": "[2] Tokenization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/tokenization-1.html" }, { "code": null, "e": 13611, "s": 13499, "text": "[3] Text Mining in Bovine Diseases — ijcaonline.org. https://www.ijcaonline.org/volume6/number10/pxc3871454.pdf" }, { "code": null, "e": 13748, "s": 13611, "text": "[4] Stemming and lemmatization — Stanford NLP Group. https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html" } ]
Sequence of execution of, instance method, static block and constructor in java?
A static block is a block of code with a static keyword. In general, these are used to initialize the static members of a class. JVM executes static blocks before the main method at the time loading a class. public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } Hello this is a static block This is main method A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type. public class MyClass { MyClass(){ System.out.println("Hello this is a constructor"); } public static void main(String args[]){ new MyClass(); } } Hello this is a constructor These are the normal methods of a class (non static), you need to invoke them using an object of the class − public class MyClass { public void demo(){ System.out.println("Hello this is an instance method"); } public static void main(String args[]){ new MyClass().demo(); } } Hello this is an instance method When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods. public class ExampleClass { static{ System.out.println("Hello this is a static block"); } ExampleClass(){ System.out.println("Hello this a constructor"); } public static void demo() { System.out.println("Hello this is an instance method"); } public static void main(String args[]){ new ExampleClass().demo(); } } Hello this is a static block Hello this a constructor Hello this is an instance method
[ { "code": null, "e": 1270, "s": 1062, "text": "A static block is a block of code with a static keyword. In general, these are used to initialize the static members of a class. JVM executes static blocks before the main method at the time loading a class." }, { "code": null, "e": 1466, "s": 1270, "text": "public class MyClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}" }, { "code": null, "e": 1515, "s": 1466, "text": "Hello this is a static block\nThis is main method" }, { "code": null, "e": 1756, "s": 1515, "text": "A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type." }, { "code": null, "e": 1926, "s": 1756, "text": "public class MyClass {\n MyClass(){\n System.out.println(\"Hello this is a constructor\");\n }\n public static void main(String args[]){\n new MyClass();\n }\n}" }, { "code": null, "e": 1954, "s": 1926, "text": "Hello this is a constructor" }, { "code": null, "e": 2063, "s": 1954, "text": "These are the normal methods of a class (non static), you need to invoke them using an object of the class −" }, { "code": null, "e": 2254, "s": 2063, "text": "public class MyClass {\n public void demo(){\n System.out.println(\"Hello this is an instance method\");\n }\n public static void main(String args[]){\n new MyClass().demo();\n }\n}" }, { "code": null, "e": 2287, "s": 2254, "text": "Hello this is an instance method" }, { "code": null, "e": 2423, "s": 2287, "text": "When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods." }, { "code": null, "e": 2784, "s": 2423, "text": "public class ExampleClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n ExampleClass(){\n System.out.println(\"Hello this a constructor\");\n }\n public static void demo() {\n System.out.println(\"Hello this is an instance method\");\n }\n public static void main(String args[]){\n new ExampleClass().demo();\n }\n}" }, { "code": null, "e": 2871, "s": 2784, "text": "Hello this is a static block\nHello this a constructor\nHello this is an instance method" } ]
VBScript UBound Function
The UBound Function returns the Largest subscript of the specified array. Hence, this value corresponds to the size of the array. UBound(ArrayName[,dimension]) ArrayName, a Required parameter. This parameter corresponds to the name of the array. ArrayName, a Required parameter. This parameter corresponds to the name of the array. dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on. dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim arr(5) arr(0) = "1" 'Number as String arr(1) = "VBScript" 'String arr(2) = 100 'Number arr(3) = 2.45 'Decimal Number arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time document.write("The Largest Subscript value of the given array is : " & UBound(arr)) ' For MultiDimension Arrays : Dim arr2(3,2) document.write( "The Largest Subscript of the first dimension of arr2 is : " & UBound(arr2,1) & "<br />") document.write( "The Largest Subscript of the Second dimension of arr2 is : " & UBound(arr2,2) & "<br />") </script> </body> </html> When the above code is saved as .HTML and executed in Internet Explorer, then it produces the following result − The Largest Subscript value of the given array is : 5 The Largest Subscript of the first dimension of arr2 is : 3 The Largest Subscript of the Second dimension of arr2 is : 2 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 2080, "text": "The UBound Function returns the Largest subscript of the specified array. Hence, this value corresponds to the size of the array." }, { "code": null, "e": 2241, "s": 2210, "text": "UBound(ArrayName[,dimension])\n" }, { "code": null, "e": 2327, "s": 2241, "text": "ArrayName, a Required parameter. This parameter corresponds to the name of the array." }, { "code": null, "e": 2413, "s": 2327, "text": "ArrayName, a Required parameter. This parameter corresponds to the name of the array." }, { "code": null, "e": 2671, "s": 2413, "text": "dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on." }, { "code": null, "e": 2929, "s": 2671, "text": "dimension, an Optional Parameter. This takes an integer value that corresponds to dimension of the array. If it is '1', then it returns the lower bound of the first dimension; if it is '2', then it returns the lower bound of the second dimension, and so on." }, { "code": null, "e": 3752, "s": 2929, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim arr(5)\n arr(0) = \"1\" 'Number as String\n arr(1) = \"VBScript\" 'String\n arr(2) = 100 'Number\n arr(3) = 2.45 'Decimal Number\n arr(4) = #10/07/2013# 'Date\n arr(5) = #12.45 PM# 'Time\n\n document.write(\"The Largest Subscript value of the given array is : \" & UBound(arr))\n\n ' For MultiDimension Arrays :\n Dim arr2(3,2)\n document.write(\n \"The Largest Subscript of the first dimension of arr2 is : \" & UBound(arr2,1) & \"<br />\")\n document.write(\n \"The Largest Subscript of the Second dimension of arr2 is : \" & UBound(arr2,2) & \"<br />\")\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 3865, "s": 3752, "text": "When the above code is saved as .HTML and executed in Internet Explorer, then it produces the following result −" }, { "code": null, "e": 4041, "s": 3865, "text": "The Largest Subscript value of the given array is : 5\nThe Largest Subscript of the first dimension of arr2 is : 3\nThe Largest Subscript of the Second dimension of arr2 is : 2\n" }, { "code": null, "e": 4074, "s": 4041, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 4091, "s": 4074, "text": " Frahaan Hussain" }, { "code": null, "e": 4098, "s": 4091, "text": " Print" }, { "code": null, "e": 4109, "s": 4098, "text": " Add Notes" } ]
Writing Professional Data Science Documentation | by Adam Gajtkowski | Towards Data Science
Documentation is an important part of being a data scientist. I propose to use R Markdown and LaTeX to document data science models. There are several desirable properties of good documentation easily accessible readable consistent across projects reproducible Using LaTeX inside R Markdown allows users to use consistent LaTeX formatting across numerous project, write professional mathematical formulas explaining given model, consistently reference figures/articles, and dynamically produce graphs from outputs of the model. LaTeX is a document preparation system originally intended for academics to introduce consistency across formatting of scientific publications. It can be also successfully used to document machine learning models. In order to use it, you need to have installed LaTeX distribution. You don’t need to install the full version of LaTeX. It is possible to use the R package tinytex to render documents with LaTeX code. tinytex::install_tinytex() To install missing LaTeX libraries, you can install it using tinytext by pasting error message as an argument. tinytex::parse_install() For example you can pass log file to fix all missing libraries error. tinytex::parse_install("filename.log") The main use of LaTex within R Markdown is typing mathematical formulas and numbering equations, adding references. Here’s the example of code I typed for Granger Causality. \begin{equation}\begin{pmatrix}U_{t} \\OLI_{t} \\\end{pmatrix}=\begin{pmatrix}\alpha_{1} \\\alpha_{2} \\\end{pmatrix}+\begin{bmatrix}\delta_{1,1,1} & \delta_{1,1,2} \\\delta_{1,2,1} & \delta_{1,2,2} \\\end{bmatrix}\begin{pmatrix}U_{t-1} \\OLI_{t-1} \\\end{pmatrix}+ ... +\begin{bmatrix}\delta_{p,1,1} & \delta_{p,1,2} \\\delta_{p,2,1} & \delta_{p,2,2} \\\end{bmatrix}\begin{pmatrix}U_{t-p} \\OLI_{t-p} \\\end{pmatrix}+\begin{pmatrix}\eta_{1t} \\\eta_{2t} \\\end{pmatrix}\end{equation} And that’s how it looked in the rendered document. I realise that the above code may look scary. LaTeX can have a steep learning curve, however once you type several first equations with google’s help, it becomes significantly easier and more automatic. R Markdown allows you to divide documents into sections/subsections, add title, add table of contents, and produce graphs which could document outputs of a given model. You can write R/Python code inside code chunks, and LaTeX formulas and text between the chunks. R Markdown document is easy to edit and render. To get more information about R Markdown, setting parameters and rendering HTML/PDFs I recommend using R Markdown Cookbook https://bookdown.org/yihui/rmarkdown-cookbook/rmarkdown-process.html Powering up agile R Markdown documentation with consistency and possibilities of LaTeX gives you a powerful tool to document data science models, which is crucial for future data scientists who will be working on your projects, as well as more technical stakeholders who may want to know more details about your work. I recommend including the R Markdown document together with rendered HTML/PDF inside your project git repository, inside the documentation folder. This will allow you to easily access more technical details of the model, and make any necessary corrections. Also, you can only use LaTeX when you render PDFs. Otherwise feel free to use HTML. List of useful resources for LaTeX and R Markdown
[ { "code": null, "e": 305, "s": 172, "text": "Documentation is an important part of being a data scientist. I propose to use R Markdown and LaTeX to document data science models." }, { "code": null, "e": 366, "s": 305, "text": "There are several desirable properties of good documentation" }, { "code": null, "e": 384, "s": 366, "text": "easily accessible" }, { "code": null, "e": 393, "s": 384, "text": "readable" }, { "code": null, "e": 420, "s": 393, "text": "consistent across projects" }, { "code": null, "e": 433, "s": 420, "text": "reproducible" }, { "code": null, "e": 700, "s": 433, "text": "Using LaTeX inside R Markdown allows users to use consistent LaTeX formatting across numerous project, write professional mathematical formulas explaining given model, consistently reference figures/articles, and dynamically produce graphs from outputs of the model." }, { "code": null, "e": 914, "s": 700, "text": "LaTeX is a document preparation system originally intended for academics to introduce consistency across formatting of scientific publications. It can be also successfully used to document machine learning models." }, { "code": null, "e": 1115, "s": 914, "text": "In order to use it, you need to have installed LaTeX distribution. You don’t need to install the full version of LaTeX. It is possible to use the R package tinytex to render documents with LaTeX code." }, { "code": null, "e": 1142, "s": 1115, "text": "tinytex::install_tinytex()" }, { "code": null, "e": 1253, "s": 1142, "text": "To install missing LaTeX libraries, you can install it using tinytext by pasting error message as an argument." }, { "code": null, "e": 1278, "s": 1253, "text": "tinytex::parse_install()" }, { "code": null, "e": 1348, "s": 1278, "text": "For example you can pass log file to fix all missing libraries error." }, { "code": null, "e": 1387, "s": 1348, "text": "tinytex::parse_install(\"filename.log\")" }, { "code": null, "e": 1561, "s": 1387, "text": "The main use of LaTex within R Markdown is typing mathematical formulas and numbering equations, adding references. Here’s the example of code I typed for Granger Causality." }, { "code": null, "e": 2046, "s": 1561, "text": "\\begin{equation}\\begin{pmatrix}U_{t} \\\\OLI_{t} \\\\\\end{pmatrix}=\\begin{pmatrix}\\alpha_{1} \\\\\\alpha_{2} \\\\\\end{pmatrix}+\\begin{bmatrix}\\delta_{1,1,1} & \\delta_{1,1,2} \\\\\\delta_{1,2,1} & \\delta_{1,2,2} \\\\\\end{bmatrix}\\begin{pmatrix}U_{t-1} \\\\OLI_{t-1} \\\\\\end{pmatrix}+ ... +\\begin{bmatrix}\\delta_{p,1,1} & \\delta_{p,1,2} \\\\\\delta_{p,2,1} & \\delta_{p,2,2} \\\\\\end{bmatrix}\\begin{pmatrix}U_{t-p} \\\\OLI_{t-p} \\\\\\end{pmatrix}+\\begin{pmatrix}\\eta_{1t} \\\\\\eta_{2t} \\\\\\end{pmatrix}\\end{equation}" }, { "code": null, "e": 2097, "s": 2046, "text": "And that’s how it looked in the rendered document." }, { "code": null, "e": 2300, "s": 2097, "text": "I realise that the above code may look scary. LaTeX can have a steep learning curve, however once you type several first equations with google’s help, it becomes significantly easier and more automatic." }, { "code": null, "e": 2805, "s": 2300, "text": "R Markdown allows you to divide documents into sections/subsections, add title, add table of contents, and produce graphs which could document outputs of a given model. You can write R/Python code inside code chunks, and LaTeX formulas and text between the chunks. R Markdown document is easy to edit and render. To get more information about R Markdown, setting parameters and rendering HTML/PDFs I recommend using R Markdown Cookbook https://bookdown.org/yihui/rmarkdown-cookbook/rmarkdown-process.html" }, { "code": null, "e": 3123, "s": 2805, "text": "Powering up agile R Markdown documentation with consistency and possibilities of LaTeX gives you a powerful tool to document data science models, which is crucial for future data scientists who will be working on your projects, as well as more technical stakeholders who may want to know more details about your work." }, { "code": null, "e": 3464, "s": 3123, "text": "I recommend including the R Markdown document together with rendered HTML/PDF inside your project git repository, inside the documentation folder. This will allow you to easily access more technical details of the model, and make any necessary corrections. Also, you can only use LaTeX when you render PDFs. Otherwise feel free to use HTML." } ]
Exquisite hand and finger tracking in web browsers with MediaPipe’s machine learning models | by LucianoSphere | Towards Data Science
Introduction Hands-on testing Testing more advanced features in MediaPipe’s CodePen example Performance of the hand tracking tool All of MediaPipe’s tracking tools Imagining the range of potential applications MediaPipe offers cross-platform machine learning-based solutions for augmented reality applications using nothing more than the regular webcams of devices. Specifically, it provides various kinds of (face, hand, body, etc.) detection and tracking algorithms which allow programmers to generate stunning visuals. The best is that many of these tools are supported in JavaScript, which means you can add superb features to your web apps and pages. I focus here on presenting MediaPipe’s hand tracking library for JavaScript, after the recent release of documentation and examples that run very well on my computer and my smartphone. This tool can detect and track hands in a video feed, and for each of them return {x,y,z} coordinates for 21 nodes (the equivalent of 4 joints per finger plus 1 palm). By simply copying and pasting the minimal code provided by MediaPipe, I got it running in 30 seconds on my website. Make sure to serve it through https, as it needs to access the webcam. Here is a first proof of it running in Firefox: Using this web page I further tested how well this could detect hands in various poses... as you see, it could get all of them right! Even those where the hand pose intrinsically involves occlusion. You can run this example yourself in this link: https://lucianoabriata.altervista.org/tests/mediapipe/hand-tracking-with-webcam-simplest.html Note: To see the models estimated for your hands, scroll down to the canvas, which may take some seconds to display! Here’s the code. See how little you need to write: <!DOCTYPE html><html><head> <meta charset="utf-8"> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js" crossorigin="anonymous"></script></head><body> <div class="container"> <video class="input_video"></video> <canvas class="output_canvas" width="1280px" height="720px"></canvas> </div></body><script type="module">const videoElement = document.getElementsByClassName('input_video')[0];const canvasElement = document.getElementsByClassName('output_canvas')[0];const canvasCtx = canvasElement.getContext('2d');function onResults(results) { canvasCtx.save(); canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height); canvasCtx.drawImage( results.image, 0, 0, canvasElement.width, canvasElement.height); if (results.multiHandLandmarks) { for (const landmarks of results.multiHandLandmarks) { drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, {color: '#00FF00', lineWidth: 5}); drawLandmarks(canvasCtx, landmarks, {color: '#FF0000', lineWidth: 2}); } } canvasCtx.restore();}const hands = new Hands({locateFile: (file) => { return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;}});hands.setOptions({ maxNumHands: 2, minDetectionConfidence: 0.5, minTrackingConfidence: 0.5});hands.onResults(onResults);const camera = new Camera(videoElement, { onFrame: async () => { await hands.send({image: videoElement}); }, width: 1280, height: 720});camera.start();</script></html> You can also see the core of this code with some basic information at MediaPipe’s site: google.github.io MediaPipe just released an example at CodePen that exemplifies various features such as: Changing webcam and swapping video (key for handling applications in various devices like phones, tablets, and laptops), Tracking either 2, 3, or 4 hands (I tried 4 hands and it still works very well!) Tuning detection parameters (although the default parameters work very well in all the conditions I tried). Besides, the CodePen example provides refresh rates in fps on running. I copied this example into a clean web page at my website. It looks like this when running: The original pen is at https://codepen.io/mediapipe/pen/RwGWYJw but you can try it more easily here: https://lucianoabriata.altervista.org/tests/mediapipe/hand-tracking-with-webcam.html I got around 25 fps when tracking 2 hands in my laptop, and around 20 fps in my smartphone. None of them is very new (laptop is a 2017 Toshiba with i7 and 8GB RAM, no special GPU; phone is a 2019 Google Pixel 3) and both have lots of programs and browser tabs open. So although there is place for improvement, I’d say the library works pretty well. With the default parameters, the example ran very well in a variety of lighting conditions. Actually I couldn’t find a situation in which it wouldn’t properly detect my hands! As of September 7th 2021 MediaPipe offers not only hand and finger tracking but also face detection and face mesh computation, iris detection, whole-body pose detection, hair segmentation, general object detection and tracking, feature matching, and automatic video cropping. Not all these tools are available (at least as of today) in JavaScript, but it could well happen that they will become available. To know more about the MediaPipe tools available for JavaScript, check this out: google.github.io And to know more about all these tools in all programming languages, check their main website: github.com In its websites, MediaPipe anticipates applications to art (see some amazing examples here: https://developers.googleblog.com/2021/07/bringing-artworks-to-life-with-ar.html), communication especially signs-based (with a project ongoing here: https://developers.googleblog.com/2021/04/signall-sdk-sign-language-interface-using-mediapipe-now-available.html), control of prothesis and robotic hands and arms (for ex. https://developers.googleblog.com/2021/05/control-your-mirru-prosthesis-with-mediapipe-hand-tracking.html). In fact Google’s meet already uses some of MediaPipe’s tools to for example control backgrounds (https://ai.googleblog.com/2020/10/background-features-in-google-meet.html). They are also using this technology to track full body poses (https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html), which could be reutilized by gym apps and who knows if maybe to produce more objective evaluation of gymnastic presentations. I can also advance applications in human-computer interfaces for augmented reality, where human users can grab objects with their hands to explore them in 3D as if they were physically in their hands. Similar to what high-end devices like the Oculus Quest or MS’s HoloLens provide, but running on any device. And as a scientist and amateur music learner, I cannot overlook the potential of the hand tracking tool for studying limb motion and coordination in drummers, guitarists, etc. Although the technology may not yet be responsive enough for normal execution speeds, I think it is already good enough for some initial investigations. I will play with this and if I find something interesting then I will let you know with a new post. Liked this article and want to tip me? [Paypal] -Thanks! I am a nature, science, technology, programming, and DIY enthusiast. Biotechnologist and chemist, in the wet lab and in computers. I write about everything that lies within my broad sphere of interests. Check out my lists for more stories. Become a Medium member to access all stories by me and other writers, and subscribe to get my new stories by email (original affiliate links of the platform).
[ { "code": null, "e": 184, "s": 171, "text": "Introduction" }, { "code": null, "e": 201, "s": 184, "text": "Hands-on testing" }, { "code": null, "e": 263, "s": 201, "text": "Testing more advanced features in MediaPipe’s CodePen example" }, { "code": null, "e": 301, "s": 263, "text": "Performance of the hand tracking tool" }, { "code": null, "e": 335, "s": 301, "text": "All of MediaPipe’s tracking tools" }, { "code": null, "e": 381, "s": 335, "text": "Imagining the range of potential applications" }, { "code": null, "e": 827, "s": 381, "text": "MediaPipe offers cross-platform machine learning-based solutions for augmented reality applications using nothing more than the regular webcams of devices. Specifically, it provides various kinds of (face, hand, body, etc.) detection and tracking algorithms which allow programmers to generate stunning visuals. The best is that many of these tools are supported in JavaScript, which means you can add superb features to your web apps and pages." }, { "code": null, "e": 1180, "s": 827, "text": "I focus here on presenting MediaPipe’s hand tracking library for JavaScript, after the recent release of documentation and examples that run very well on my computer and my smartphone. This tool can detect and track hands in a video feed, and for each of them return {x,y,z} coordinates for 21 nodes (the equivalent of 4 joints per finger plus 1 palm)." }, { "code": null, "e": 1415, "s": 1180, "text": "By simply copying and pasting the minimal code provided by MediaPipe, I got it running in 30 seconds on my website. Make sure to serve it through https, as it needs to access the webcam. Here is a first proof of it running in Firefox:" }, { "code": null, "e": 1614, "s": 1415, "text": "Using this web page I further tested how well this could detect hands in various poses... as you see, it could get all of them right! Even those where the hand pose intrinsically involves occlusion." }, { "code": null, "e": 1756, "s": 1614, "text": "You can run this example yourself in this link: https://lucianoabriata.altervista.org/tests/mediapipe/hand-tracking-with-webcam-simplest.html" }, { "code": null, "e": 1873, "s": 1756, "text": "Note: To see the models estimated for your hands, scroll down to the canvas, which may take some seconds to display!" }, { "code": null, "e": 1924, "s": 1873, "text": "Here’s the code. See how little you need to write:" }, { "code": null, "e": 3758, "s": 1924, "text": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <script src=\"https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/@mediapipe/hands/hands.js\" crossorigin=\"anonymous\"></script></head><body> <div class=\"container\"> <video class=\"input_video\"></video> <canvas class=\"output_canvas\" width=\"1280px\" height=\"720px\"></canvas> </div></body><script type=\"module\">const videoElement = document.getElementsByClassName('input_video')[0];const canvasElement = document.getElementsByClassName('output_canvas')[0];const canvasCtx = canvasElement.getContext('2d');function onResults(results) { canvasCtx.save(); canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height); canvasCtx.drawImage( results.image, 0, 0, canvasElement.width, canvasElement.height); if (results.multiHandLandmarks) { for (const landmarks of results.multiHandLandmarks) { drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, {color: '#00FF00', lineWidth: 5}); drawLandmarks(canvasCtx, landmarks, {color: '#FF0000', lineWidth: 2}); } } canvasCtx.restore();}const hands = new Hands({locateFile: (file) => { return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;}});hands.setOptions({ maxNumHands: 2, minDetectionConfidence: 0.5, minTrackingConfidence: 0.5});hands.onResults(onResults);const camera = new Camera(videoElement, { onFrame: async () => { await hands.send({image: videoElement}); }, width: 1280, height: 720});camera.start();</script></html>" }, { "code": null, "e": 3846, "s": 3758, "text": "You can also see the core of this code with some basic information at MediaPipe’s site:" }, { "code": null, "e": 3863, "s": 3846, "text": "google.github.io" }, { "code": null, "e": 3952, "s": 3863, "text": "MediaPipe just released an example at CodePen that exemplifies various features such as:" }, { "code": null, "e": 4073, "s": 3952, "text": "Changing webcam and swapping video (key for handling applications in various devices like phones, tablets, and laptops)," }, { "code": null, "e": 4154, "s": 4073, "text": "Tracking either 2, 3, or 4 hands (I tried 4 hands and it still works very well!)" }, { "code": null, "e": 4262, "s": 4154, "text": "Tuning detection parameters (although the default parameters work very well in all the conditions I tried)." }, { "code": null, "e": 4333, "s": 4262, "text": "Besides, the CodePen example provides refresh rates in fps on running." }, { "code": null, "e": 4425, "s": 4333, "text": "I copied this example into a clean web page at my website. It looks like this when running:" }, { "code": null, "e": 4611, "s": 4425, "text": "The original pen is at https://codepen.io/mediapipe/pen/RwGWYJw but you can try it more easily here: https://lucianoabriata.altervista.org/tests/mediapipe/hand-tracking-with-webcam.html" }, { "code": null, "e": 4960, "s": 4611, "text": "I got around 25 fps when tracking 2 hands in my laptop, and around 20 fps in my smartphone. None of them is very new (laptop is a 2017 Toshiba with i7 and 8GB RAM, no special GPU; phone is a 2019 Google Pixel 3) and both have lots of programs and browser tabs open. So although there is place for improvement, I’d say the library works pretty well." }, { "code": null, "e": 5136, "s": 4960, "text": "With the default parameters, the example ran very well in a variety of lighting conditions. Actually I couldn’t find a situation in which it wouldn’t properly detect my hands!" }, { "code": null, "e": 5623, "s": 5136, "text": "As of September 7th 2021 MediaPipe offers not only hand and finger tracking but also face detection and face mesh computation, iris detection, whole-body pose detection, hair segmentation, general object detection and tracking, feature matching, and automatic video cropping. Not all these tools are available (at least as of today) in JavaScript, but it could well happen that they will become available. To know more about the MediaPipe tools available for JavaScript, check this out:" }, { "code": null, "e": 5640, "s": 5623, "text": "google.github.io" }, { "code": null, "e": 5735, "s": 5640, "text": "And to know more about all these tools in all programming languages, check their main website:" }, { "code": null, "e": 5746, "s": 5735, "text": "github.com" }, { "code": null, "e": 6268, "s": 5746, "text": "In its websites, MediaPipe anticipates applications to art (see some amazing examples here: https://developers.googleblog.com/2021/07/bringing-artworks-to-life-with-ar.html), communication especially signs-based (with a project ongoing here: https://developers.googleblog.com/2021/04/signall-sdk-sign-language-interface-using-mediapipe-now-available.html), control of prothesis and robotic hands and arms (for ex. https://developers.googleblog.com/2021/05/control-your-mirru-prosthesis-with-mediapipe-hand-tracking.html)." }, { "code": null, "e": 6709, "s": 6268, "text": "In fact Google’s meet already uses some of MediaPipe’s tools to for example control backgrounds (https://ai.googleblog.com/2020/10/background-features-in-google-meet.html). They are also using this technology to track full body poses (https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html), which could be reutilized by gym apps and who knows if maybe to produce more objective evaluation of gymnastic presentations." }, { "code": null, "e": 7018, "s": 6709, "text": "I can also advance applications in human-computer interfaces for augmented reality, where human users can grab objects with their hands to explore them in 3D as if they were physically in their hands. Similar to what high-end devices like the Oculus Quest or MS’s HoloLens provide, but running on any device." }, { "code": null, "e": 7447, "s": 7018, "text": "And as a scientist and amateur music learner, I cannot overlook the potential of the hand tracking tool for studying limb motion and coordination in drummers, guitarists, etc. Although the technology may not yet be responsive enough for normal execution speeds, I think it is already good enough for some initial investigations. I will play with this and if I find something interesting then I will let you know with a new post." }, { "code": null, "e": 7504, "s": 7447, "text": "Liked this article and want to tip me? [Paypal] -Thanks!" } ]
What are the clustering types? What is Gaussian Mixture Model? Clustering for image segmentation, Clustering for data preprocessing | Towards Data Science
Table of Contents1. Introduction2. Clustering Types2.1. K-Means-----Theory-----The optimal number of clusters-----Implementation2.2. Mini-Batch K-Means2.3. DBSCAN2.4. Agglomerative Clustering2.5. Mean-Shift2.6. BIRCH3. Image Segmentation with Clustering4. Data Preprocessing with Clustering5. Gaussian Mixture Model-----Implementation-----How to select the number of clusters?6. Summary Unlabeled datasets can be grouped by considering their similar properties with the unsupervised learning technique. However, the point of view of these similar features is different in each algorithm. Unsupervised learning provides detailed information about the dataset as well as labeling the data. With this acquired information, the dataset can be rearranged and made more understandable. In this way, unsupervised learning is used in customer segmentation, image segmentation, genetics (clustering DNA patterns), recommender systems (grouping together users with similar viewing patterns), anomaly detection, and many more. New and concise components are obtained according to the statistical properties of the dataset with the PCA that is one of the most frequently used dimensionality reduction techniques and mentioned in the previous article. This article explains clustering types, using clustering for image segmentation, data preprocessing with clustering, and Gaussian mixtures method in detail. All explanations are supported with python implementation. K-means clustering is one of the frequently used clustering algorithms. The underlying idea is to place the samples according to the distance from the center of the clusters in the number determined by the user. The code block below explains how the k-means cluster is built from scratch. The centers of the determined number of clusters are randomly placed in the dataset. All samples are assigned to the closest center, this closeness is calculated with Euclidian Distance in the code block above, but different calculation methods can also be used such as Manhattan Distance. Centers to which samples are assigned update their location (average) according to their population. Stage 2, that is, the distances of the samples from the center are recalculated and the assignment to the nearest center takes place, and it is repeated. Stage 3, each cluster center recenters itself according to the dataset. This process continues to an equilibrium state. The above code block is visualized in figure 1 by importing the steps described verbally here from the mglearn library. The scratch above is imported with the sklearn library and exemplified in the practical section. As it is known, there are methods such as .fit, .predict, .transform. The K-means algorithm imported with .fit performs as described above by placing the samples in the clusters, updating the centers of the clusters, and repeating these operations. When the equilibrium state is reached, that is, there is no change, the algorithm is completed. The center of the clusters can be seen with Kmeans.cluster_centers_. With the .predict we can predict the cluster of any external sample we wonder which cluster it will belong to. With .transform, the distance between the sample and each cluster can be obtained as a matrix. Each row of this matrix represents the distance of the sample from each cluster center. Choosing the smallest value (assigning the sample to the nearest center) is called hard clustering. At this point, it is worth mentioning that the new dataset (with .transform) to be obtained as a result of the distances of each sample to the selected number of clusters is actually a very effective nonlinear dimensionality reduction technique. Finding the inertia values for each k-value is one of the ways to choose the optimal number of clusters. Inertia is the sum of squared error for each cluster. According to this definition, the number k with the lowest inertia value would give us the most accurate result. Although it is theoretically correct, when we generalize the model, the place where the inertia value reaches the smallest value, i.e. 0, is k = sample numbers, that is, the point where each sample accepts the cluster. From this point, it is the best way to examine the graph and determine the breakpoint in order to choose the most accurate cluster. Figure 2 shows the inertia-number of cluster plots of datasets grouped with k-means in the practical part. Looking at the graphs, it is seen that diffraction (elbow) occurs at n=2 point, which is interpreted as the optimum number of clusters to be selected. Another method is to determine the silhouette score and compare the silhouette score values in the cluster numbers. Silhouette score is the measure that takes a value between -1 and 1 and is equal to (b — a) / max(a, b), where a is the mean distance to the other instances in the same cluster and b is the mean nearest-cluster distance. By definition, the highest score serves to determine the best cluster level. The only downside is computational complexity. In Figure 3, the silhouette score graphic of the practical part is shown. As can be seen, the highest value is obtained at the level of 2 clusters. A value of 1 is not added because at least 2 clusters are required to determine the Silhouette score. Datasets presented in the Sklearn library are imported and then the K-Means Clustering algorithm is applied to both of them as follow: Elbow graphs and the result of the silhouette are already shown above and the effect of k-means is shown in figure 4. As the name suggests, it updates the cluster center in mini-batches instead of the entire dataset. As expected, the inertia value is higher, although it shortens the time compared to k-means. It can be used in large datasets. It is implemented in Python as follow: The results are almost the same compared to K-Means as seen in Figure 5. We can compare the principle of Density-Based Spatial Clustering of Applications with Noise (DBSCAN) to sorting out the chains in a box full of chains. Clusters are created with the proximity of the datasets to each other instead of the proximity of the samples in the population to the centers, and the number of clusters is not set by the user. In more formal terms, the algorithm groups samples that are close to each other at a shorter distance than the € hyperparameter set by the user. Another hyperparameter, min_samples, is the minimum number of samples required to assign this collection as a cluster. As it can be understood from the expression and the name, grouping is done according to the dense of the dataset. The samples in the dense region are called core samples. The above recipe is visualized as in figure 6, using the mglearn library. When eps=1.5 is examined, while 3 different groups are created and all samples are labeled in case min_samples=2. Because all datasets are closer to the nearest data than eps=1.5. In the same case, when min_samples=5 is set, only 5 data clusters are created, while 7 data remains unlabeled. Because data is far from eps=1.5 distance to the created cluster. In addition, the reason why new clusters are not formed is that there are not 5 samples close to each other at eps=1.5 distance. As it is seen that, the number of clusters is determined according to the hyperparameters set with DBSCAN. It is useful to use in anomaly detection with the appropriate settings, as would be expected. It has been applied to datasets in the following code block: Moons dataset is not suitable for separating with k-means in terms of structure, but after the data standardization process, it is clustered quite elegantly with DBSCAN. Unlike K-Means, DBSCAN does not contain the .predict method in its structure, so it cannot be determined which cluster the external data belongs to according to this dataset. But DBSCAN components are extracted with dbscan.component_ then called matrix X; the labels are extracted with the dbscan.labels_ method and then called y, at the final step, they are trained with the KNeighbourClassifier, the model becomes useful for external data as well. Each sample starts as a cluster, and mini-clusters (samples clusters) are combined with user-selected conditions until the specified number of clusters is reached. These conditions are: linkage= ‘ward’: minimize the variance of the clusters being merged (default) linkage= ‘average’: uses the average of the distance of each observation linkage= ‘complete’: uses the maximum distances between all observations of the two sets. linkage =‘single’: uses the minimum of the distances between all observations of the two sets. In addition, the distance between clusters can be adjusted with the affinity hyperparameter. “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”. Agglomerative clustering is visualized with mglearn library as seen in figure 8. As it is seen that, the clustering process starts from the closest samples and the merger continues until the number of clusters is determined by the user. Due to its structure, agglomerative clustering does not include the .predict method, just like DBSCAN. External data is estimated with the fit_predict method. Agglomerative clustering works by generating hierarchical clusterings. The best way to visualize these hierarchical clusterings is to create dendrograms. It is applied to our moons dataset with the following code block: The output of the code block is as in figure 9. If we interpret it from low level to high level, each sample is a cluster. So, we have a number of samples clusters. Since the number of them is too high, merging processes take place at the bottom, which is seen in red bulk, and clustering is performed as in figure 10. This process will continue until the number of clusters to be determined by the user and will be interrupted at the specified point. It starts with a circle placed in the dataset and moves to reveal the mean value of the data in this circle. After reaching its new position, the average of the data inside is calculated and recentered again. This process is repeated until the equilibrium state. The places with high density can be defined as a density-based algorithm as they will pull the average value towards them (ie mean-shift). We can also detect different clusters within dense regions, assuming we reduce the size of the circle. Once the bandwidth is changed, lots of clusters are created as seen in Figure 12. bandwith=0.75 is set in the moon dataset and the results are as follow: The BIRCH (Balanced Iterative Reducing and Clustering using Hierarchies) is a tree-based algorithm suitable for large datasets. Compared to Mini Batch k means, it gives much faster results with similar success rates. Since the clustering process is tree-based, it can quickly assign the samples to the clusters without storing them with the model created. That’s why it’s fast. However, since it is tree-based, it is recommended to use it when the number of features is not more than 20. Since we have dealt with the sklearn library enough until this section, let’s apply K-Means to the image seen in figure 13 by using the CV2 library. The following code block has been applied to the image at various k values. The results of K-Means are as follows: The results of DBSCAN are as follow: If we interpret it from the image dataset, there are hundreds of features and if these features are made with clustering, it can be considered as the features are grouped and dimensionality reduction is made. Classification with the decision tree algorithm with and without clustering applied to the Load_digits dataset was done in the following code block: It is seen that the score ratio increases from 83 to 88, when the number of clusters is set to 40. GMM is a probabilistic model that assumes that a dataset is made up of a combination of individual Gaussians with unknown parameters. With K-means, as mentioned above, hard clustering is done and the sample is assigned to the nearest cluster. Considering factors such as distribution and density in k means datasets, which is a cluster center-based unsupervised learning technique, k-means may give misleading results. For the density, it can be seen above that DBSCAN is more successful. If we tackle according to the distribution, the clustering performance would be better in GMM. Let’s define the building block, Gaussian, to better understand the GMM. What is the gaussian which is the main component and what does it reveal? Gaussian Distribution represents a distinctive bell-shaped curve when a sample is plotted in a histogram. Normal (Gaussian) Distribution occurs when there are random factors that interact with the measure. In a normal distribution majority of data points will have a measure that is similar to the mean and the mean value is the center of the bell shape curve. However, fewer data points have values much larger or smaller than the mean value. The width of the curve in the distribution corresponds to the std. In the 1.0 std interval, 68.3% of the whole dataset takes place, while in the 2.0 std interval there is 95.4%. Figure 15 shows the normal (gaussian) distribution and mean, std points drawn from the histogram. Gaussian Mixtures Model groups as a result of the combination of Gaussians, which reveals the statistical distribution in the dataset. Variance(for 1D) or covariance(for 2D) values derived from the standard deviation value created in Gaussian play an active role at this point. K-means does not consider the variance value, only distributes it according to the proximity to the cluster center. While Gaussian Distribution generates probabilistic ratios about which cluster the data belongs to (the sum of these ratios=1), that means soft clustering; K-Means clustering prefers hard clustering. It should also be noted that GMM uses the Expectation-Maximization algorithm to fit the Gaussians that form it. Gaussian Mixture Models will be covered in detail in subsequent articles. Since it is pretty easy to implement GMM to the sklearn dataset, it has been applied to the flower image used in image segmentation in the code block below: It is necessary to mention one of the essential hyperparameters, covariance_type, in the implementation section. Covariance_type can be: covariance_type=‘full’: each component has its own general covariance matrix, which means clusters can be on any shape, size, orientation (default) covariance_type=‘tied’: all components share the same general covariance matrix, which means all clusters have the same ellipsoidal shape, size, orientation covariance_type=‘diag’: each component has its own diagonal covariance matrix, which means clusters can be any ellipsoidal size. covariance_type=‘spherical’: each component has its own single variance, which means All clusters must be spherical, but they can have different diameters. It was mentioned above that silhouette score or inertia can be used in the k-means header. However, because the cluster shape for the Gaussian Mixture Model may not be spherical or may be of different sizes, it may be misleading to choose according to a certain metric system. It is more correct to use the Bayesian Information Criterion or Akaike Information Criterion when choosing the best number of clusters for GMM. AIC and BIC are the probabilistic model selection techniques that are used for scoring and selecting the best model. Let’s look at the bic&aic values of the moons dataset above and visualize it: As can be seen, both AIC and BIC are maximum in the case of n=2. In the middle part of the code block, their performances against different covariance types are also tested and the result is shown in figure 19. It is seen that the best BIC value is obtained covariance_type=‘spherical’ for each k value. Most of the clustering techniques are discussed above. Theoretical parts of them were explained and these were implemented in python with basic examples. The image that includes a summary of clustering techniques is shown in figure 20. The previous article involves one of the most useful dimensionality reduction techniques, that is, Principal Component Analysis (PCA). This article covers the clustering types and some of their usage areas with Python implementation. Remaining subjects such as Outlier Detection, Expectation-maximization meta-algorithm (EM), Self-Organization Maps (SOM), Fuzzy C Means, etc. will be discussed in further articles.
[ { "code": null, "e": 558, "s": 171, "text": "Table of Contents1. Introduction2. Clustering Types2.1. K-Means-----Theory-----The optimal number of clusters-----Implementation2.2. Mini-Batch K-Means2.3. DBSCAN2.4. Agglomerative Clustering2.5. Mean-Shift2.6. BIRCH3. Image Segmentation with Clustering4. Data Preprocessing with Clustering5. Gaussian Mixture Model-----Implementation-----How to select the number of clusters?6. Summary" }, { "code": null, "e": 1626, "s": 558, "text": "Unlabeled datasets can be grouped by considering their similar properties with the unsupervised learning technique. However, the point of view of these similar features is different in each algorithm. Unsupervised learning provides detailed information about the dataset as well as labeling the data. With this acquired information, the dataset can be rearranged and made more understandable. In this way, unsupervised learning is used in customer segmentation, image segmentation, genetics (clustering DNA patterns), recommender systems (grouping together users with similar viewing patterns), anomaly detection, and many more. New and concise components are obtained according to the statistical properties of the dataset with the PCA that is one of the most frequently used dimensionality reduction techniques and mentioned in the previous article. This article explains clustering types, using clustering for image segmentation, data preprocessing with clustering, and Gaussian mixtures method in detail. All explanations are supported with python implementation." }, { "code": null, "e": 1915, "s": 1626, "text": "K-means clustering is one of the frequently used clustering algorithms. The underlying idea is to place the samples according to the distance from the center of the clusters in the number determined by the user. The code block below explains how the k-means cluster is built from scratch." }, { "code": null, "e": 2700, "s": 1915, "text": "The centers of the determined number of clusters are randomly placed in the dataset. All samples are assigned to the closest center, this closeness is calculated with Euclidian Distance in the code block above, but different calculation methods can also be used such as Manhattan Distance. Centers to which samples are assigned update their location (average) according to their population. Stage 2, that is, the distances of the samples from the center are recalculated and the assignment to the nearest center takes place, and it is repeated. Stage 3, each cluster center recenters itself according to the dataset. This process continues to an equilibrium state. The above code block is visualized in figure 1 by importing the steps described verbally here from the mglearn library." }, { "code": null, "e": 3851, "s": 2700, "text": "The scratch above is imported with the sklearn library and exemplified in the practical section. As it is known, there are methods such as .fit, .predict, .transform. The K-means algorithm imported with .fit performs as described above by placing the samples in the clusters, updating the centers of the clusters, and repeating these operations. When the equilibrium state is reached, that is, there is no change, the algorithm is completed. The center of the clusters can be seen with Kmeans.cluster_centers_. With the .predict we can predict the cluster of any external sample we wonder which cluster it will belong to. With .transform, the distance between the sample and each cluster can be obtained as a matrix. Each row of this matrix represents the distance of the sample from each cluster center. Choosing the smallest value (assigning the sample to the nearest center) is called hard clustering. At this point, it is worth mentioning that the new dataset (with .transform) to be obtained as a result of the distances of each sample to the selected number of clusters is actually a very effective nonlinear dimensionality reduction technique." }, { "code": null, "e": 4474, "s": 3851, "text": "Finding the inertia values for each k-value is one of the ways to choose the optimal number of clusters. Inertia is the sum of squared error for each cluster. According to this definition, the number k with the lowest inertia value would give us the most accurate result. Although it is theoretically correct, when we generalize the model, the place where the inertia value reaches the smallest value, i.e. 0, is k = sample numbers, that is, the point where each sample accepts the cluster. From this point, it is the best way to examine the graph and determine the breakpoint in order to choose the most accurate cluster." }, { "code": null, "e": 4732, "s": 4474, "text": "Figure 2 shows the inertia-number of cluster plots of datasets grouped with k-means in the practical part. Looking at the graphs, it is seen that diffraction (elbow) occurs at n=2 point, which is interpreted as the optimum number of clusters to be selected." }, { "code": null, "e": 5267, "s": 4732, "text": "Another method is to determine the silhouette score and compare the silhouette score values in the cluster numbers. Silhouette score is the measure that takes a value between -1 and 1 and is equal to (b — a) / max(a, b), where a is the mean distance to the other instances in the same cluster and b is the mean nearest-cluster distance. By definition, the highest score serves to determine the best cluster level. The only downside is computational complexity. In Figure 3, the silhouette score graphic of the practical part is shown." }, { "code": null, "e": 5341, "s": 5267, "text": "As can be seen, the highest value is obtained at the level of 2 clusters." }, { "code": null, "e": 5443, "s": 5341, "text": "A value of 1 is not added because at least 2 clusters are required to determine the Silhouette score." }, { "code": null, "e": 5578, "s": 5443, "text": "Datasets presented in the Sklearn library are imported and then the K-Means Clustering algorithm is applied to both of them as follow:" }, { "code": null, "e": 5696, "s": 5578, "text": "Elbow graphs and the result of the silhouette are already shown above and the effect of k-means is shown in figure 4." }, { "code": null, "e": 5961, "s": 5696, "text": "As the name suggests, it updates the cluster center in mini-batches instead of the entire dataset. As expected, the inertia value is higher, although it shortens the time compared to k-means. It can be used in large datasets. It is implemented in Python as follow:" }, { "code": null, "e": 6034, "s": 5961, "text": "The results are almost the same compared to K-Means as seen in Figure 5." }, { "code": null, "e": 6890, "s": 6034, "text": "We can compare the principle of Density-Based Spatial Clustering of Applications with Noise (DBSCAN) to sorting out the chains in a box full of chains. Clusters are created with the proximity of the datasets to each other instead of the proximity of the samples in the population to the centers, and the number of clusters is not set by the user. In more formal terms, the algorithm groups samples that are close to each other at a shorter distance than the € hyperparameter set by the user. Another hyperparameter, min_samples, is the minimum number of samples required to assign this collection as a cluster. As it can be understood from the expression and the name, grouping is done according to the dense of the dataset. The samples in the dense region are called core samples. The above recipe is visualized as in figure 6, using the mglearn library." }, { "code": null, "e": 7577, "s": 6890, "text": "When eps=1.5 is examined, while 3 different groups are created and all samples are labeled in case min_samples=2. Because all datasets are closer to the nearest data than eps=1.5. In the same case, when min_samples=5 is set, only 5 data clusters are created, while 7 data remains unlabeled. Because data is far from eps=1.5 distance to the created cluster. In addition, the reason why new clusters are not formed is that there are not 5 samples close to each other at eps=1.5 distance. As it is seen that, the number of clusters is determined according to the hyperparameters set with DBSCAN. It is useful to use in anomaly detection with the appropriate settings, as would be expected." }, { "code": null, "e": 7638, "s": 7577, "text": "It has been applied to datasets in the following code block:" }, { "code": null, "e": 8258, "s": 7638, "text": "Moons dataset is not suitable for separating with k-means in terms of structure, but after the data standardization process, it is clustered quite elegantly with DBSCAN. Unlike K-Means, DBSCAN does not contain the .predict method in its structure, so it cannot be determined which cluster the external data belongs to according to this dataset. But DBSCAN components are extracted with dbscan.component_ then called matrix X; the labels are extracted with the dbscan.labels_ method and then called y, at the final step, they are trained with the KNeighbourClassifier, the model becomes useful for external data as well." }, { "code": null, "e": 8444, "s": 8258, "text": "Each sample starts as a cluster, and mini-clusters (samples clusters) are combined with user-selected conditions until the specified number of clusters is reached. These conditions are:" }, { "code": null, "e": 8522, "s": 8444, "text": "linkage= ‘ward’: minimize the variance of the clusters being merged (default)" }, { "code": null, "e": 8595, "s": 8522, "text": "linkage= ‘average’: uses the average of the distance of each observation" }, { "code": null, "e": 8685, "s": 8595, "text": "linkage= ‘complete’: uses the maximum distances between all observations of the two sets." }, { "code": null, "e": 8780, "s": 8685, "text": "linkage =‘single’: uses the minimum of the distances between all observations of the two sets." }, { "code": null, "e": 9020, "s": 8780, "text": "In addition, the distance between clusters can be adjusted with the affinity hyperparameter. “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”. Agglomerative clustering is visualized with mglearn library as seen in figure 8." }, { "code": null, "e": 9555, "s": 9020, "text": "As it is seen that, the clustering process starts from the closest samples and the merger continues until the number of clusters is determined by the user. Due to its structure, agglomerative clustering does not include the .predict method, just like DBSCAN. External data is estimated with the fit_predict method. Agglomerative clustering works by generating hierarchical clusterings. The best way to visualize these hierarchical clusterings is to create dendrograms. It is applied to our moons dataset with the following code block:" }, { "code": null, "e": 9603, "s": 9555, "text": "The output of the code block is as in figure 9." }, { "code": null, "e": 10007, "s": 9603, "text": "If we interpret it from low level to high level, each sample is a cluster. So, we have a number of samples clusters. Since the number of them is too high, merging processes take place at the bottom, which is seen in red bulk, and clustering is performed as in figure 10. This process will continue until the number of clusters to be determined by the user and will be interrupted at the specified point." }, { "code": null, "e": 10594, "s": 10007, "text": "It starts with a circle placed in the dataset and moves to reveal the mean value of the data in this circle. After reaching its new position, the average of the data inside is calculated and recentered again. This process is repeated until the equilibrium state. The places with high density can be defined as a density-based algorithm as they will pull the average value towards them (ie mean-shift). We can also detect different clusters within dense regions, assuming we reduce the size of the circle. Once the bandwidth is changed, lots of clusters are created as seen in Figure 12." }, { "code": null, "e": 10666, "s": 10594, "text": "bandwith=0.75 is set in the moon dataset and the results are as follow:" }, { "code": null, "e": 11154, "s": 10666, "text": "The BIRCH (Balanced Iterative Reducing and Clustering using Hierarchies) is a tree-based algorithm suitable for large datasets. Compared to Mini Batch k means, it gives much faster results with similar success rates. Since the clustering process is tree-based, it can quickly assign the samples to the clusters without storing them with the model created. That’s why it’s fast. However, since it is tree-based, it is recommended to use it when the number of features is not more than 20." }, { "code": null, "e": 11379, "s": 11154, "text": "Since we have dealt with the sklearn library enough until this section, let’s apply K-Means to the image seen in figure 13 by using the CV2 library. The following code block has been applied to the image at various k values." }, { "code": null, "e": 11418, "s": 11379, "text": "The results of K-Means are as follows:" }, { "code": null, "e": 11455, "s": 11418, "text": "The results of DBSCAN are as follow:" }, { "code": null, "e": 11813, "s": 11455, "text": "If we interpret it from the image dataset, there are hundreds of features and if these features are made with clustering, it can be considered as the features are grouped and dimensionality reduction is made. Classification with the decision tree algorithm with and without clustering applied to the Load_digits dataset was done in the following code block:" }, { "code": null, "e": 11912, "s": 11813, "text": "It is seen that the score ratio increases from 83 to 88, when the number of clusters is set to 40." }, { "code": null, "e": 12643, "s": 11912, "text": "GMM is a probabilistic model that assumes that a dataset is made up of a combination of individual Gaussians with unknown parameters. With K-means, as mentioned above, hard clustering is done and the sample is assigned to the nearest cluster. Considering factors such as distribution and density in k means datasets, which is a cluster center-based unsupervised learning technique, k-means may give misleading results. For the density, it can be seen above that DBSCAN is more successful. If we tackle according to the distribution, the clustering performance would be better in GMM. Let’s define the building block, Gaussian, to better understand the GMM. What is the gaussian which is the main component and what does it reveal?" }, { "code": null, "e": 13363, "s": 12643, "text": "Gaussian Distribution represents a distinctive bell-shaped curve when a sample is plotted in a histogram. Normal (Gaussian) Distribution occurs when there are random factors that interact with the measure. In a normal distribution majority of data points will have a measure that is similar to the mean and the mean value is the center of the bell shape curve. However, fewer data points have values much larger or smaller than the mean value. The width of the curve in the distribution corresponds to the std. In the 1.0 std interval, 68.3% of the whole dataset takes place, while in the 2.0 std interval there is 95.4%. Figure 15 shows the normal (gaussian) distribution and mean, std points drawn from the histogram." }, { "code": null, "e": 14143, "s": 13363, "text": "Gaussian Mixtures Model groups as a result of the combination of Gaussians, which reveals the statistical distribution in the dataset. Variance(for 1D) or covariance(for 2D) values derived from the standard deviation value created in Gaussian play an active role at this point. K-means does not consider the variance value, only distributes it according to the proximity to the cluster center. While Gaussian Distribution generates probabilistic ratios about which cluster the data belongs to (the sum of these ratios=1), that means soft clustering; K-Means clustering prefers hard clustering. It should also be noted that GMM uses the Expectation-Maximization algorithm to fit the Gaussians that form it. Gaussian Mixture Models will be covered in detail in subsequent articles." }, { "code": null, "e": 14300, "s": 14143, "text": "Since it is pretty easy to implement GMM to the sklearn dataset, it has been applied to the flower image used in image segmentation in the code block below:" }, { "code": null, "e": 14437, "s": 14300, "text": "It is necessary to mention one of the essential hyperparameters, covariance_type, in the implementation section. Covariance_type can be:" }, { "code": null, "e": 14585, "s": 14437, "text": "covariance_type=‘full’: each component has its own general covariance matrix, which means clusters can be on any shape, size, orientation (default)" }, { "code": null, "e": 14742, "s": 14585, "text": "covariance_type=‘tied’: all components share the same general covariance matrix, which means all clusters have the same ellipsoidal shape, size, orientation" }, { "code": null, "e": 14871, "s": 14742, "text": "covariance_type=‘diag’: each component has its own diagonal covariance matrix, which means clusters can be any ellipsoidal size." }, { "code": null, "e": 15027, "s": 14871, "text": "covariance_type=‘spherical’: each component has its own single variance, which means All clusters must be spherical, but they can have different diameters." }, { "code": null, "e": 15448, "s": 15027, "text": "It was mentioned above that silhouette score or inertia can be used in the k-means header. However, because the cluster shape for the Gaussian Mixture Model may not be spherical or may be of different sizes, it may be misleading to choose according to a certain metric system. It is more correct to use the Bayesian Information Criterion or Akaike Information Criterion when choosing the best number of clusters for GMM." }, { "code": null, "e": 15565, "s": 15448, "text": "AIC and BIC are the probabilistic model selection techniques that are used for scoring and selecting the best model." }, { "code": null, "e": 15643, "s": 15565, "text": "Let’s look at the bic&aic values of the moons dataset above and visualize it:" }, { "code": null, "e": 15854, "s": 15643, "text": "As can be seen, both AIC and BIC are maximum in the case of n=2. In the middle part of the code block, their performances against different covariance types are also tested and the result is shown in figure 19." }, { "code": null, "e": 15947, "s": 15854, "text": "It is seen that the best BIC value is obtained covariance_type=‘spherical’ for each k value." }, { "code": null, "e": 16183, "s": 15947, "text": "Most of the clustering techniques are discussed above. Theoretical parts of them were explained and these were implemented in python with basic examples. The image that includes a summary of clustering techniques is shown in figure 20." }, { "code": null, "e": 16417, "s": 16183, "text": "The previous article involves one of the most useful dimensionality reduction techniques, that is, Principal Component Analysis (PCA). This article covers the clustering types and some of their usage areas with Python implementation." } ]
Differences between wait() and join() methods in Java
In multithreading when we deal with threads there comes the requirement of pause and start a thread for this Threading provides two methods wait and join which are used for the same. The following are the important differences between wait() and join(). JavaTester.java Live Demo public class JavaTester extends Thread { static Object lock = new Object(); static int n; int i; String name; JavaTester(String name, int i) { this.name = name; this.i = i; } @Override public void run() { try { synchronized (lock) { while (i != n) { lock.wait(); } System.out.println(name + " started"); n++; lock.notifyAll(); } synchronized (lock) { while (i != n - 4) { lock.wait(); } System.out.println(name + " finished"); n++; lock.notifyAll(); } } catch (InterruptedException e) { } } public static void main(String[] args) throws Exception { new JavaTester("a", 0).start(); new JavaTester("b", 1).start(); new JavaTester("c", 2).start(); new JavaTester("d", 3).start(); } } a started b started c started d started a finished b finished c finished d finished
[ { "code": null, "e": 1245, "s": 1062, "text": "In multithreading when we deal with threads there comes the requirement of pause and start a thread for this Threading provides two methods wait and join which are used for the same." }, { "code": null, "e": 1316, "s": 1245, "text": "The following are the important differences between wait() and join()." }, { "code": null, "e": 1332, "s": 1316, "text": "JavaTester.java" }, { "code": null, "e": 1343, "s": 1332, "text": " Live Demo" }, { "code": null, "e": 2303, "s": 1343, "text": "public class JavaTester extends Thread {\n static Object lock = new Object();\n static int n;\n int i;\n String name;\n JavaTester(String name, int i) {\n this.name = name;\n this.i = i;\n }\n @Override\n public void run() {\n try {\n synchronized (lock) {\n while (i != n) {\n lock.wait();\n }\n System.out.println(name + \" started\");\n n++;\n lock.notifyAll();\n }\n synchronized (lock) {\n while (i != n - 4) {\n lock.wait();\n }\n System.out.println(name + \" finished\");\n n++;\n lock.notifyAll();\n }\n }\n catch (InterruptedException e) {\n }\n }\n public static void main(String[] args) throws Exception {\n new JavaTester(\"a\", 0).start();\n new JavaTester(\"b\", 1).start();\n new JavaTester(\"c\", 2).start();\n new JavaTester(\"d\", 3).start();\n }\n}" }, { "code": null, "e": 2387, "s": 2303, "text": "a started\nb started\nc started\nd started\na finished\nb finished\nc finished\nd finished" } ]
kasai’s Algorithm
Kasai’s Algorithm is used to get the Longest Common Prefix (LCP) array from suffix array. At first suffix arrays are found. After that Kasai's algorithm takes the suffix array list to find LCP. For the LCP array, it takes O(m log n), where m is pattern length and n is the length of the text. The Kasai’s Algorithm, it takes O(n) for searching the pattern in the main string. Input: Main String: “banana” Output: Suffix Array : 5 3 1 0 4 2 Common Prefix Array : 1 3 0 0 2 0 buildSuffixArray(text) Input: The main string Output: The suffix array, built from the main text Begin n := size of text for i := 0 to n, do suffArray[i].index := i suffArray[i].rank[0] := text[i] if (i+1) < n, then suffArray[i].rank[1] := text[i+1] else suffArray[i].rank[1] := -1 do sort the suffix array define index array to store indexes for k := 4 to (2*n)-1, increase k by k*2, do currRank := 0 prevRank := suffArray[0].rank[0] suffArray[0].rank[0] := currRank index[suffArray[0].index] = 0 for all character index i of text, do if suffArray[i].rank[0] = prevRank AND suffArray[i].rank[1] = suffArray[i-1].rank[1], then prevRank := suffArray[i].rank[0] suffArray[i].rank[0] := currRank else prevRank := suffArray[i].rank[0] suffArray[i].rank[0] := currRank + 1 currRank := currRank + 1 index[suffArray[i].index] := i done for all character index i of text, do nextIndex := suffArray[i].index + k/2 if nextIndex< n, then suffArray[i].rank[1] := suffArray[index[nextIndex]].rank[0] else suffArray[i].rank[1] := -1 done sort the suffArray done for all character index i of text, do insert suffArray[i].index into suffVector done End kasaiAlgorithm(text, suffVector) Input − The main text, and the suffix vector as a list of suffixes Output: The location of where longest common prefix is found Begin n := size of suffVector define longPrefix list of size n and fill all entries with 0 define suffInverse list of size n and fill all entries with 0 for all index values ‘i’ of suffVector, do suffInverse[suffVector[i]] = i done k := 0 for i := 0 to n-1, do if suffInverse[i] = n-1 then k :=0 ignore the bottom part and go for next iteration. j := suffVector[suffInverse[i]+1] while (i+k)<n AND (j+k) < n and text[i+k] = text[j+k], do increase k by 1 done longPrefix[suffInverse[i]] := k if k > 0 then decrease k by 1 done return longPrefix End #include<iostream> #include<vector> #include<algorithm> using namespace std; struct suffix { int index; int rank[2]; // To store rank pair }; bool compare(suffix s1, suffix s2) { //compare suffixes for sort function if(s1.rank[0] == s2.rank[0]) { if(s1.rank[1] < s2.rank[1]) return true; else return false; }else { if(s1.rank[0] < s2.rank[0]) return true; else return false; } } vector<int> buildSuffixArray(string mainString) { int n = mainString.size(); suffix suffixArray[n]; for (int i = 0; i < n; i++) { suffixArray[i].index = i; suffixArray[i].rank[0] = mainString[i] - 'a'; //store old rank suffixArray[i].rank[1] = ((i+1)<n)?(mainString[i+1]-'a'):-1; //rank after alphabetical ordering } sort(suffixArray, suffixArray+n, compare); //sort suffix array upto first 2 characters int index[n]; //index in suffixArray for (int k = 4; k < 2*n; k = k*2) { //increase k as power of 2 int currRank = 0; int prevRank = suffixArray[0].rank[0]; suffixArray[0].rank[0] = currRank; index[suffixArray[0].index] = 0; for (int i = 1; i < n; i++) { // Assigning rank to all suffix if (suffixArray[i].rank[0] == prevRank && suffixArray[i].rank[1] == suffixArray[i-1].rank[1]) { prevRank = suffixArray[i].rank[0]; suffixArray[i].rank[0] = currRank; } else{ //increment rank and assign prevRank = suffixArray[i].rank[0]; suffixArray[i].rank[0] = ++currRank; } index[suffixArray[i].index] = i; } for (int i = 0; i < n; i++) { // Assign next rank to every suffix int nextIndex = suffixArray[i].index + k/2; suffixArray[i].rank[1] = (nextIndex < n)? suffixArray[index[nextIndex]].rank[0]: -1; } sort(suffixArray, suffixArray+n, compare); //sort upto first k characters } vector<int>suffixVector; for (int i = 0; i < n; i++) suffixVector.push_back(suffixArray[i].index); //index of all suffix to suffix vector return suffixVector; } vector<int> kasaiAlgorithm(string mainString, vector<int> suffixVector) { int n = suffixVector.size(); vector<int> longPrefix(n, 0); //size n and initialize with 0 vector<int> suffixInverse(n, 0); for (int i=0; i < n; i++) suffixInverse[suffixVector[i]] = i; //fill values of inverse Suffix list int k = 0; for (int i=0; i<n; i++) { //for all suffix in main string if (suffixInverse[i] == n-1) { //when suffix at position (n-1) k = 0; continue; } int j = suffixVector[suffixInverse[i]+1]; //nest string of suffix list while (i+k<n && j+k<n && mainString[i+k]==mainString[j+k]) //start from kth index k++; longPrefix[suffixInverse[i]] = k; // prefix for the current suffix. if (k>0) k--; //remofe first character of string } return longPrefix; } void showArray(vector<int> vec) { vector<int>::iterator it; for (it = vec.begin(); it < vec.end() ; it++) cout << *it << " "; cout << endl; } int main() { string mainString = "banana"; vector<int>suffixArray = buildSuffixArray(mainString); int n = suffixArray.size(); cout<< "Suffix Array : "<<endl; showArray(suffixArray); vector<int>commonPrefix = kasaiAlgorithm(mainString, suffixArray); cout<< "\nCommon Prefix Array : "<<endl; showArray(commonPrefix); } Suffix Array : 5 3 1 0 4 2 Common Prefix Array : 1 3 0 0 2 0
[ { "code": null, "e": 1256, "s": 1062, "text": "Kasai’s Algorithm is used to get the Longest Common Prefix (LCP) array from suffix array. At first suffix arrays are found. After that Kasai's algorithm takes the suffix array list to find LCP." }, { "code": null, "e": 1438, "s": 1256, "text": "For the LCP array, it takes O(m log n), where m is pattern length and n is the length of the text. The Kasai’s Algorithm, it takes O(n) for searching the pattern in the main string." }, { "code": null, "e": 1536, "s": 1438, "text": "Input:\nMain String: “banana”\nOutput:\nSuffix Array :\n5 3 1 0 4 2\nCommon Prefix Array :\n1 3 0 0 2 0" }, { "code": null, "e": 1559, "s": 1536, "text": "buildSuffixArray(text)" }, { "code": null, "e": 1582, "s": 1559, "text": "Input: The main string" }, { "code": null, "e": 1633, "s": 1582, "text": "Output: The suffix array, built from the main text" }, { "code": null, "e": 2961, "s": 1633, "text": "Begin\n n := size of text\n\n for i := 0 to n, do\n suffArray[i].index := i\n suffArray[i].rank[0] := text[i]\n if (i+1) < n, then\n suffArray[i].rank[1] := text[i+1]\n else\n suffArray[i].rank[1] := -1\n do\n\n sort the suffix array\n define index array to store indexes\n\n for k := 4 to (2*n)-1, increase k by k*2, do\n currRank := 0\n prevRank := suffArray[0].rank[0]\n suffArray[0].rank[0] := currRank\n index[suffArray[0].index] = 0\n\n for all character index i of text, do\n if suffArray[i].rank[0] = prevRank AND suffArray[i].rank[1] =\n suffArray[i-1].rank[1], then\n prevRank := suffArray[i].rank[0]\n suffArray[i].rank[0] := currRank\n else\n prevRank := suffArray[i].rank[0]\n suffArray[i].rank[0] := currRank + 1\n currRank := currRank + 1\n index[suffArray[i].index] := i\n done\n\n for all character index i of text, do\n nextIndex := suffArray[i].index + k/2\n if nextIndex< n, then\n suffArray[i].rank[1] := suffArray[index[nextIndex]].rank[0]\n else\n suffArray[i].rank[1] := -1\n done\n sort the suffArray\n done\n\n for all character index i of text, do\n insert suffArray[i].index into suffVector\n done\nEnd" }, { "code": null, "e": 2994, "s": 2961, "text": "kasaiAlgorithm(text, suffVector)" }, { "code": null, "e": 3061, "s": 2994, "text": "Input − The main text, and the suffix vector as a list of suffixes" }, { "code": null, "e": 3122, "s": 3061, "text": "Output: The location of where longest common prefix is found" }, { "code": null, "e": 3811, "s": 3122, "text": "Begin\n n := size of suffVector\n define longPrefix list of size n and fill all entries with 0\n define suffInverse list of size n and fill all entries with 0\n\n for all index values ‘i’ of suffVector, do\n suffInverse[suffVector[i]] = i\n done\n\n k := 0\n for i := 0 to n-1, do\n if suffInverse[i] = n-1 then\n k :=0\n ignore the bottom part and go for next iteration.\n j := suffVector[suffInverse[i]+1]\n\n while (i+k)<n AND (j+k) < n and text[i+k] = text[j+k], do\n increase k by 1\n done\n longPrefix[suffInverse[i]] := k\n if k > 0 then\n decrease k by 1\n done\n return longPrefix\nEnd" }, { "code": null, "e": 7332, "s": 3811, "text": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nstruct suffix {\n int index;\n int rank[2]; // To store rank pair\n};\n\nbool compare(suffix s1, suffix s2) { //compare suffixes for sort function\n if(s1.rank[0] == s2.rank[0]) {\n if(s1.rank[1] < s2.rank[1])\n return true;\n else\n return false;\n }else {\n if(s1.rank[0] < s2.rank[0])\n return true;\n else\n return false;\n }\n}\n\nvector<int> buildSuffixArray(string mainString) {\n int n = mainString.size();\n suffix suffixArray[n];\n\n for (int i = 0; i < n; i++) {\n suffixArray[i].index = i;\n suffixArray[i].rank[0] = mainString[i] - 'a'; //store old rank\n suffixArray[i].rank[1] = ((i+1)<n)?(mainString[i+1]-'a'):-1; //rank after alphabetical ordering\n }\n\n sort(suffixArray, suffixArray+n, compare); //sort suffix array upto first 2 characters\n int index[n]; //index in suffixArray\n\n for (int k = 4; k < 2*n; k = k*2) { //increase k as power of 2\n int currRank = 0;\n int prevRank = suffixArray[0].rank[0];\n suffixArray[0].rank[0] = currRank;\n index[suffixArray[0].index] = 0;\n\n for (int i = 1; i < n; i++) { // Assigning rank to all suffix\n if (suffixArray[i].rank[0] == prevRank && suffixArray[i].rank[1] == suffixArray[i-1].rank[1]) {\n prevRank = suffixArray[i].rank[0];\n suffixArray[i].rank[0] = currRank;\n } else{ //increment rank and assign\n prevRank = suffixArray[i].rank[0];\n suffixArray[i].rank[0] = ++currRank;\n }\n index[suffixArray[i].index] = i;\n }\n\n for (int i = 0; i < n; i++) { // Assign next rank to every suffix\n int nextIndex = suffixArray[i].index + k/2;\n suffixArray[i].rank[1] = (nextIndex < n)? suffixArray[index[nextIndex]].rank[0]: -1;\n }\n sort(suffixArray, suffixArray+n, compare); //sort upto first k characters\n }\n\n vector<int>suffixVector;\n for (int i = 0; i < n; i++)\n suffixVector.push_back(suffixArray[i].index); //index of all suffix to suffix vector\n return suffixVector;\n}\n\nvector<int> kasaiAlgorithm(string mainString, vector<int> suffixVector) {\n int n = suffixVector.size();\n vector<int> longPrefix(n, 0); //size n and initialize with 0\n vector<int> suffixInverse(n, 0);\n\n for (int i=0; i < n; i++)\n suffixInverse[suffixVector[i]] = i; //fill values of inverse Suffix list\n int k = 0;\n for (int i=0; i<n; i++) { //for all suffix in main string\n if (suffixInverse[i] == n-1) { //when suffix at position (n-1)\n k = 0;\n continue;\n }\n\n int j = suffixVector[suffixInverse[i]+1]; //nest string of suffix list\n while (i+k<n && j+k<n && mainString[i+k]==mainString[j+k]) //start from kth index\n k++;\n longPrefix[suffixInverse[i]] = k; // prefix for the current suffix.\n if (k>0)\n k--; //remofe first character of string\n }\n return longPrefix;\n}\n\nvoid showArray(vector<int> vec) {\n vector<int>::iterator it;\n\n for (it = vec.begin(); it < vec.end() ; it++)\n cout << *it << \" \";\n cout << endl;\n}\n\nint main() {\n string mainString = \"banana\";\n vector<int>suffixArray = buildSuffixArray(mainString);\n int n = suffixArray.size();\n\n cout<< \"Suffix Array : \"<<endl;\n showArray(suffixArray);\n\n vector<int>commonPrefix = kasaiAlgorithm(mainString, suffixArray);\n\n cout<< \"\\nCommon Prefix Array : \"<<endl;\n showArray(commonPrefix);\n}" }, { "code": null, "e": 7393, "s": 7332, "text": "Suffix Array :\n5 3 1 0 4 2\nCommon Prefix Array :\n1 3 0 0 2 0" } ]
How to read a Matrix from user in Java? - GeeksforGeeks
05 Mar, 2019 Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard. // Java program to read a matrix from user import java.util.Scanner; public class MatrixFromUser { // Function to read matrix public static void readMatrixByUser() { int m, n, i, j; Scanner in = null; try { in = new Scanner(System.in); System.out.println("Enter the number " + "of rows of the matrix"); m = in.nextInt(); System.out.println("Enter the number " + "of columns of the matrix"); n = in.nextInt(); // Declare the matrix int first[][] = new int[m][n]; // Read the matrix values System.out.println("Enter the elements of the matrix"); for (i = 0; i < m; i++) for (j = 0; j < n; j++) first[i][j] = in.nextInt(); // Display the elements of the matrix System.out.println("Elements of the matrix are"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) System.out.print(first[i][j] + " "); System.out.println(); } } catch (Exception e) { } finally { in.close(); } } // Driver code public static void main(String[] args) { readMatrixByUser(); }} Enter the number of rows of the matrix 2 Enter the number of columns of the matrix 2 Enter the elements of the matrix 1 2 3 4 Elements of the matrix are 1 2 3 4 Java-Arrays Picked Java Matrix Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Stream In Java Constructors in Java Generics in Java Exceptions in Java Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Print a given matrix in spiral form Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
[ { "code": null, "e": 24026, "s": 23998, "text": "\n05 Mar, 2019" }, { "code": null, "e": 24150, "s": 24026, "text": "Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard." }, { "code": "// Java program to read a matrix from user import java.util.Scanner; public class MatrixFromUser { // Function to read matrix public static void readMatrixByUser() { int m, n, i, j; Scanner in = null; try { in = new Scanner(System.in); System.out.println(\"Enter the number \" + \"of rows of the matrix\"); m = in.nextInt(); System.out.println(\"Enter the number \" + \"of columns of the matrix\"); n = in.nextInt(); // Declare the matrix int first[][] = new int[m][n]; // Read the matrix values System.out.println(\"Enter the elements of the matrix\"); for (i = 0; i < m; i++) for (j = 0; j < n; j++) first[i][j] = in.nextInt(); // Display the elements of the matrix System.out.println(\"Elements of the matrix are\"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) System.out.print(first[i][j] + \" \"); System.out.println(); } } catch (Exception e) { } finally { in.close(); } } // Driver code public static void main(String[] args) { readMatrixByUser(); }}", "e": 25508, "s": 24150, "text": null }, { "code": null, "e": 25672, "s": 25508, "text": "Enter the number of rows of the matrix 2\nEnter the number of columns of the matrix 2\nEnter the elements of the matrix\n1\n2\n3\n4\nElements of the matrix are\n1 2 \n3 4 \n" }, { "code": null, "e": 25684, "s": 25672, "text": "Java-Arrays" }, { "code": null, "e": 25691, "s": 25684, "text": "Picked" }, { "code": null, "e": 25696, "s": 25691, "text": "Java" }, { "code": null, "e": 25703, "s": 25696, "text": "Matrix" }, { "code": null, "e": 25710, "s": 25703, "text": "Matrix" }, { "code": null, "e": 25715, "s": 25710, "text": "Java" }, { "code": null, "e": 25813, "s": 25715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25822, "s": 25813, "text": "Comments" }, { "code": null, "e": 25835, "s": 25822, "text": "Old Comments" }, { "code": null, "e": 25881, "s": 25835, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25896, "s": 25881, "text": "Stream In Java" }, { "code": null, "e": 25917, "s": 25896, "text": "Constructors in Java" }, { "code": null, "e": 25934, "s": 25917, "text": "Generics in Java" }, { "code": null, "e": 25953, "s": 25934, "text": "Exceptions in Java" }, { "code": null, "e": 25988, "s": 25953, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 26032, "s": 25988, "text": "Program to find largest element in an array" }, { "code": null, "e": 26063, "s": 26032, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 26099, "s": 26063, "text": "Print a given matrix in spiral form" } ]
Create and publish your own Python package | by Mike Huls | Towards Data Science
You are probably familiar with requests, Pandas, Numpy and many other packages that you can install with pip. Now it’s time to create your own package! In this article we’ll go through the required steps to package and publish your Python code for the whole world to pip install. First we’ll look at packaging your code, then how we can publish it to make it accessible. (Would you rather share your code with just a select few people like coworkers? It’s also possible to allow people to pip install a package from a private repository. This even works when including your package in a Docker container!) For this article, I’ve created a few truly essential functions that I’d like to share with the world. Let’s create a package called “mikes_toolbox” that people can use by simply pip install mikes_toolbox. First we’ll sketch an overview of how the installation process works: if someone calls pip install mikes_toolbox the code has to come from somewhere. Pip searches for a package with that name on PyPi; the Python Package Index. You can think of this as a YouTube for Python packages. First we’ll package our code and then upload it to PyPi so that others can find our package, download it and install it. First we’ll package our code. We’ll create a project directory called ‘toolbox_project’ that contains the following directories and files: toolbox_project mikes_toolbox __init__.py functions.py decorators.py LICENSE.txt README.md setup.cfg setup.py The content of the project folder consists of two parts: the mikes_toolbox folder and 4 additional files. The folder is our actual package that contains our source code. The 4 additional files contain information on how to install the package and some additional information. mikes_toolbox is our actual package and contains all of our source code. Make sure to name this folder the same as your desired package name. In my case it has this content: mikes_toolbox/function.py and decorators.pyThis is my source code. Function.py contains a function called weirdCase() for example; a function that’ll turn a string completely unreadable. mikes_toolbox/__init__.pyThis file is required. It tells python that mikes_toolbox is a Python package folder. You can keep it empty. Optionally you can include import statements here to make importing code from your package easier. An example:Include from functions import weirdCase. This way people don’t have to from mikes_toolbox.functions import weirdCase once the package is installed, instead they can just from mikes_toolbox import weirdCase. Describes how people can use your license. Just select one from this site and paste the contents in this file. This file contains information about the package: what does it do? What are its features? How to install and use it? Check out an example here or here. This file is written in markup. Check out this site for an editor that already contains some example markup; just edit it to fit your needs. This is a simple file that just contains the code below. It refers to the README.md. [metadata]description-file = README.md This file makes sure the package installs correctly. Copy the code below and modify it where needed. Most entries are logical but the download_url needs a little explanation (see below): When you pip install pandas pip searches for pandas on PyPi. Once found, PyPi tells pip where it can download the package. Most of the time this is a file on a git repository. The download_url keyword refers to the location of this file. In order for us to get a URL we first have put our source code somewhere that pip can reach. The best way to do this is to upload your code to a GitHub repo and create a release. This process is super-easy, here are the steps: Create a repository (name doesn’t have to match package name but it is more orderly).In your repo, on the right side; click “create a new release”Fill in “tag version” to be the same as in setup.py (version keyword)Give the release a title and description. This is not reflected in the package, this is purely for keeping an overview in your repoClick “publish release”Copy the link address of “Source Code (tar.gz)Paste the copied link address as the value op the download_url in setup.py Create a repository (name doesn’t have to match package name but it is more orderly). In your repo, on the right side; click “create a new release” Fill in “tag version” to be the same as in setup.py (version keyword) Give the release a title and description. This is not reflected in the package, this is purely for keeping an overview in your repo Click “publish release” Copy the link address of “Source Code (tar.gz) Paste the copied link address as the value op the download_url in setup.py That’s it! Your package is now downloadable and installable. The next step is to take care of distribution. The only thing we’ve done so far is packaged our code and uploaded it to GitHub, pip still has no idea our package exists. So let’s make sure pip can find our package so that people can install it. If you want to post video’s to YouTube you need to create an account first. If you want to upload packages to PyPi you also need to create an account first. Go to PyPi and register an account. Confirm your email address before continuing. This creates a tar.gz file that contains everything needed to run the package. Open a terminal, cd to your project directory and execute the command below: python setup.py sdist (Unfamiliar with the terminal? Check out this article for the absolute basics) We’re ready to upload our package! First we need to pip install Twine which’ll help us upload. Simply pip install twine. The last step is to actually upload the package. In a terminal, cd to your project directory if you’re not there already and execute python -m twine upload dist/* Twine will ask you for your PyPi credential but after that your package should be uploaded! Create a new python project and (optionally) spin up a new virtual environment. Then pip install mikes_toolbox. Test the code by calling from mikes_toolbox import weirdCaseprint(weirdCase("This function is essential and very important")) If you update your package you need to make sure to update the version in setup.py and create a new release with the same tag on GitHub. Also update the download_url in setup.py.Once you’ve done this users can update your package using pip install mikes_toolbox --upgrade In these easy steps you’ve learnt how to package your code and publish it to the world using PyPi and pip. In addition you’ve created a central place where your code lives which can be uses for tracking bugs, posting issues or requesting new features. No more sharing code via mail I hope I’ve clarified a lot of the process of creating and distributing Python packages. If you have suggestions/clarifications please comment so I can improve this article. In the meantime, check out my other articles on all kinds of programming-related topics. Happy coding! — Mike P.S: Like what I’m doing? Follow me!
[ { "code": null, "e": 543, "s": 172, "text": "You are probably familiar with requests, Pandas, Numpy and many other packages that you can install with pip. Now it’s time to create your own package! In this article we’ll go through the required steps to package and publish your Python code for the whole world to pip install. First we’ll look at packaging your code, then how we can publish it to make it accessible." }, { "code": null, "e": 778, "s": 543, "text": "(Would you rather share your code with just a select few people like coworkers? It’s also possible to allow people to pip install a package from a private repository. This even works when including your package in a Docker container!)" }, { "code": null, "e": 983, "s": 778, "text": "For this article, I’ve created a few truly essential functions that I’d like to share with the world. Let’s create a package called “mikes_toolbox” that people can use by simply pip install mikes_toolbox." }, { "code": null, "e": 1387, "s": 983, "text": "First we’ll sketch an overview of how the installation process works: if someone calls pip install mikes_toolbox the code has to come from somewhere. Pip searches for a package with that name on PyPi; the Python Package Index. You can think of this as a YouTube for Python packages. First we’ll package our code and then upload it to PyPi so that others can find our package, download it and install it." }, { "code": null, "e": 1526, "s": 1387, "text": "First we’ll package our code. We’ll create a project directory called ‘toolbox_project’ that contains the following directories and files:" }, { "code": null, "e": 1672, "s": 1526, "text": "toolbox_project mikes_toolbox __init__.py functions.py decorators.py LICENSE.txt README.md setup.cfg setup.py" }, { "code": null, "e": 1948, "s": 1672, "text": "The content of the project folder consists of two parts: the mikes_toolbox folder and 4 additional files. The folder is our actual package that contains our source code. The 4 additional files contain information on how to install the package and some additional information." }, { "code": null, "e": 2122, "s": 1948, "text": "mikes_toolbox is our actual package and contains all of our source code. Make sure to name this folder the same as your desired package name. In my case it has this content:" }, { "code": null, "e": 2309, "s": 2122, "text": "mikes_toolbox/function.py and decorators.pyThis is my source code. Function.py contains a function called weirdCase() for example; a function that’ll turn a string completely unreadable." }, { "code": null, "e": 2760, "s": 2309, "text": "mikes_toolbox/__init__.pyThis file is required. It tells python that mikes_toolbox is a Python package folder. You can keep it empty. Optionally you can include import statements here to make importing code from your package easier. An example:Include from functions import weirdCase. This way people don’t have to from mikes_toolbox.functions import weirdCase once the package is installed, instead they can just from mikes_toolbox import weirdCase." }, { "code": null, "e": 2871, "s": 2760, "text": "Describes how people can use your license. Just select one from this site and paste the contents in this file." }, { "code": null, "e": 3164, "s": 2871, "text": "This file contains information about the package: what does it do? What are its features? How to install and use it? Check out an example here or here. This file is written in markup. Check out this site for an editor that already contains some example markup; just edit it to fit your needs." }, { "code": null, "e": 3249, "s": 3164, "text": "This is a simple file that just contains the code below. It refers to the README.md." }, { "code": null, "e": 3288, "s": 3249, "text": "[metadata]description-file = README.md" }, { "code": null, "e": 3475, "s": 3288, "text": "This file makes sure the package installs correctly. Copy the code below and modify it where needed. Most entries are logical but the download_url needs a little explanation (see below):" }, { "code": null, "e": 3940, "s": 3475, "text": "When you pip install pandas pip searches for pandas on PyPi. Once found, PyPi tells pip where it can download the package. Most of the time this is a file on a git repository. The download_url keyword refers to the location of this file. In order for us to get a URL we first have put our source code somewhere that pip can reach. The best way to do this is to upload your code to a GitHub repo and create a release. This process is super-easy, here are the steps:" }, { "code": null, "e": 4430, "s": 3940, "text": "Create a repository (name doesn’t have to match package name but it is more orderly).In your repo, on the right side; click “create a new release”Fill in “tag version” to be the same as in setup.py (version keyword)Give the release a title and description. This is not reflected in the package, this is purely for keeping an overview in your repoClick “publish release”Copy the link address of “Source Code (tar.gz)Paste the copied link address as the value op the download_url in setup.py" }, { "code": null, "e": 4516, "s": 4430, "text": "Create a repository (name doesn’t have to match package name but it is more orderly)." }, { "code": null, "e": 4578, "s": 4516, "text": "In your repo, on the right side; click “create a new release”" }, { "code": null, "e": 4648, "s": 4578, "text": "Fill in “tag version” to be the same as in setup.py (version keyword)" }, { "code": null, "e": 4780, "s": 4648, "text": "Give the release a title and description. This is not reflected in the package, this is purely for keeping an overview in your repo" }, { "code": null, "e": 4804, "s": 4780, "text": "Click “publish release”" }, { "code": null, "e": 4851, "s": 4804, "text": "Copy the link address of “Source Code (tar.gz)" }, { "code": null, "e": 4926, "s": 4851, "text": "Paste the copied link address as the value op the download_url in setup.py" }, { "code": null, "e": 5034, "s": 4926, "text": "That’s it! Your package is now downloadable and installable. The next step is to take care of distribution." }, { "code": null, "e": 5232, "s": 5034, "text": "The only thing we’ve done so far is packaged our code and uploaded it to GitHub, pip still has no idea our package exists. So let’s make sure pip can find our package so that people can install it." }, { "code": null, "e": 5471, "s": 5232, "text": "If you want to post video’s to YouTube you need to create an account first. If you want to upload packages to PyPi you also need to create an account first. Go to PyPi and register an account. Confirm your email address before continuing." }, { "code": null, "e": 5627, "s": 5471, "text": "This creates a tar.gz file that contains everything needed to run the package. Open a terminal, cd to your project directory and execute the command below:" }, { "code": null, "e": 5649, "s": 5627, "text": "python setup.py sdist" }, { "code": null, "e": 5728, "s": 5649, "text": "(Unfamiliar with the terminal? Check out this article for the absolute basics)" }, { "code": null, "e": 5849, "s": 5728, "text": "We’re ready to upload our package! First we need to pip install Twine which’ll help us upload. Simply pip install twine." }, { "code": null, "e": 5982, "s": 5849, "text": "The last step is to actually upload the package. In a terminal, cd to your project directory if you’re not there already and execute" }, { "code": null, "e": 6012, "s": 5982, "text": "python -m twine upload dist/*" }, { "code": null, "e": 6104, "s": 6012, "text": "Twine will ask you for your PyPi credential but after that your package should be uploaded!" }, { "code": null, "e": 6241, "s": 6104, "text": "Create a new python project and (optionally) spin up a new virtual environment. Then pip install mikes_toolbox. Test the code by calling" }, { "code": null, "e": 6342, "s": 6241, "text": "from mikes_toolbox import weirdCaseprint(weirdCase(\"This function is essential and very important\"))" }, { "code": null, "e": 6578, "s": 6342, "text": "If you update your package you need to make sure to update the version in setup.py and create a new release with the same tag on GitHub. Also update the download_url in setup.py.Once you’ve done this users can update your package using" }, { "code": null, "e": 6614, "s": 6578, "text": "pip install mikes_toolbox --upgrade" }, { "code": null, "e": 6896, "s": 6614, "text": "In these easy steps you’ve learnt how to package your code and publish it to the world using PyPi and pip. In addition you’ve created a central place where your code lives which can be uses for tracking bugs, posting issues or requesting new features. No more sharing code via mail" }, { "code": null, "e": 7173, "s": 6896, "text": "I hope I’ve clarified a lot of the process of creating and distributing Python packages. If you have suggestions/clarifications please comment so I can improve this article. In the meantime, check out my other articles on all kinds of programming-related topics. Happy coding!" }, { "code": null, "e": 7180, "s": 7173, "text": "— Mike" } ]
Java XML - Quick Guide
XML is a simple text-based language which was designed to store and transport data in plain text format. It stands for Extensible Markup Language. Following are some of the salient features of XML. XML is a markup language. XML is a markup language. XML is a tag based language like HTML. XML is a tag based language like HTML. XML tags are not predefined like HTML. XML tags are not predefined like HTML. You can define your own tags which is why it is called extensible language. You can define your own tags which is why it is called extensible language. XML tags are designed to be self-descriptive. XML tags are designed to be self-descriptive. XML is W3C Recommendation for data storage and data transfer. XML is W3C Recommendation for data storage and data transfer. <?xml version = "1.0"?> <Class> <Name>First</Name> <Sections> <Section> <Name>A</Name> <Students> <Student>Rohan</Student> <Student>Mohan</Student> <Student>Sohan</Student> <Student>Lalit</Student> <Student>Vinay</Student> </Students> </Section> <Section> <Name>B</Name> <Students> <Student>Robert</Student> <Student>Julie</Student> <Student>Kalie</Student> <Student>Michael</Student> </Students> </Section> </Sections> </Class> Following are the advantages that XML provides − Technology agnostic − Being plain text, XML is technology independent. It can be used by any technology for data storage and data transfer purpose. Technology agnostic − Being plain text, XML is technology independent. It can be used by any technology for data storage and data transfer purpose. Human readable − XML uses simple text format. It is human readable and understandable. Human readable − XML uses simple text format. It is human readable and understandable. Extensible − In XML, custom tags can be created and used very easily. Extensible − In XML, custom tags can be created and used very easily. Allow Validation − Using XSD, DTD and XML structures can be validated easily. Allow Validation − Using XSD, DTD and XML structures can be validated easily. Following are the disadvantages of using XML − Redundant Syntax − Normally XML files contain a lot of repetitive terms. Redundant Syntax − Normally XML files contain a lot of repetitive terms. Verbose − Being a verbose language, XML file size increases the transmission and storage costs. Verbose − Being a verbose language, XML file size increases the transmission and storage costs. XML Parsing refers to going through an XML document in order to access or modify data. XML Parser provides a way to access or modify data in an XML document. Java provides multiple options to parse XML documents. Following are the various types of parsers which are commonly used to parse XML documents. Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory. Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory. SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory. SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory. JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way. JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way. StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way. StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way. XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT. XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT. DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP. DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP. There are JAXB and XSLT APIs available to handle XML parsing in object-oriented way. We'll elaborate each parser in detail in the subsequent chapters of this tutorial. The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). It defines an interface that enables programs to access and update the style, structure, and contents of XML documents. XML parsers that support DOM implement this interface. You should use a DOM parser when − You need to know a lot about the structure of a document. You need to know a lot about the structure of a document. You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to use the information in an XML document more than once. You need to use the information in an XML document more than once. When you parse an XML document with a DOM parser, you get back a tree structure that contains all of the elements of your document. The DOM provides a variety of functions you can use to examine the contents and structure of the document. The DOM is a common interface for manipulating document structures. One of its design goals is that Java code written for one DOM-compliant parser should run on any other DOM-compliant parser without having to do any modifications. The DOM defines several Java interfaces. Here are the most common interfaces − Node − The base datatype of the DOM. Node − The base datatype of the DOM. Element − The vast majority of the objects you'll deal with are Elements. Element − The vast majority of the objects you'll deal with are Elements. Attr − Represents an attribute of an element. Attr − Represents an attribute of an element. Text − The actual content of an Element or Attr. Text − The actual content of an Element or Attr. Document − Represents the entire XML document. A Document object is often referred to as a DOM tree. Document − Represents the entire XML document. A Document object is often referred to as a DOM tree. When you are working with DOM, there are several methods you'll use often − Document.getDocumentElement() − Returns the root element of the document. Document.getDocumentElement() − Returns the root element of the document. Node.getFirstChild() − Returns the first child of a given Node. Node.getFirstChild() − Returns the first child of a given Node. Node.getLastChild() − Returns the last child of a given Node. Node.getLastChild() − Returns the last child of a given Node. Node.getNextSibling() − These methods return the next sibling of a given Node. Node.getNextSibling() − These methods return the next sibling of a given Node. Node.getPreviousSibling() − These methods return the previous sibling of a given Node. Node.getPreviousSibling() − These methods return the previous sibling of a given Node. Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name. Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name. Following are the steps used while parsing a document using JDOM Parser. Import XML-related packages. Create a DocumentBuilder Create a Document from a file or stream Extract the root element Examine attributes Examine sub-elements import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuilder xmlStringBuilder = new StringBuilder(); xmlStringBuilder.append("<?xml version="1.0"?> "); ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes("UTF-8")); Document doc = builder.parse(input); Element root = document.getDocumentElement(); //returns specific attribute getAttribute("attributeName"); //returns a Map (table) of names/values getAttributes(); //returns a list of subelements of specified name getElementsByTagName("subelementName"); //returns a list of all child nodes getChildNodes(); Here is the input xml file that we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; public class DomParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("student"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Student roll no : " + eElement.getAttribute("rollno")); System.out.println("First Name : " + eElement .getElementsByTagName("firstname") .item(0) .getTextContent()); System.out.println("Last Name : " + eElement .getElementsByTagName("lastname") .item(0) .getTextContent()); System.out.println("Nick Name : " + eElement .getElementsByTagName("nickname") .item(0) .getTextContent()); System.out.println("Marks : " + eElement .getElementsByTagName("marks") .item(0) .getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result − Root element :class ---------------------------- Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singn Nick Name : jazz Marks : 90 Here is the input xml file that we need to query − <?xml version = "1.0"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferarri 101</carname> <carname type = "sports car">Ferarri 201</carname> <carname type = "sports car">Ferarri 301</carname> </supercars> <supercars company = "Lamborgini"> <carname>Lamborgini 001</carname> <carname>Lamborgini 002</carname> <carname>Lamborgini 003</carname> </supercars> <luxurycars company = "Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars> package com.tutorialspoint.xml; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class QueryXmlFileDemo { public static void main(String argv[]) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.print("Root element: "); System.out.println(doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("supercars"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :"); System.out.print(nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.print("company : "); System.out.println(eElement.getAttribute("company")); NodeList carNameList = eElement.getElementsByTagName("carname"); for (int count = 0; count < carNameList.getLength(); count++) { Node node1 = carNameList.item(count); if (node1.getNodeType() == node1.ELEMENT_NODE) { Element car = (Element) node1; System.out.print("car name : "); System.out.println(car.getTextContent()); System.out.print("car type : "); System.out.println(car.getAttribute("type")); } } } } } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result − Root element: cars ---------------------------- Current Element : supercarscompany : Ferrari car name : Ferarri 101 car type : formula one car name : Ferarri 201 car type : sports car car name : Ferarri 301 car type : sports car Current Element : supercarscompany : Lamborgini car name : Lamborgini 001 car type : car name : Lamborgini 002 car type : car name : Lamborgini 003 car type : Here is the XML we need to create − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> package com.tutorialspoint.xml; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; public class CreateXmlFileDemo { public static void main(String argv[]) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("cars"); doc.appendChild(rootElement); // supercars element Element supercar = doc.createElement("supercars"); rootElement.appendChild(supercar); // setting attribute to element Attr attr = doc.createAttribute("company"); attr.setValue("Ferrari"); supercar.setAttributeNode(attr); // carname element Element carname = doc.createElement("carname"); Attr attrType = doc.createAttribute("type"); attrType.setValue("formula one"); carname.setAttributeNode(attrType); carname.appendChild(doc.createTextNode("Ferrari 101")); supercar.appendChild(carname); Element carname1 = doc.createElement("carname"); Attr attrType1 = doc.createAttribute("type"); attrType1.setValue("sports"); carname1.setAttributeNode(attrType1); carname1.appendChild(doc.createTextNode("Ferrari 202")); supercar.appendChild(carname1); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\cars.xml")); transformer.transform(source, result); // Output to console for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> Here is the input xml file we need to modify − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> <luxurycars company = "Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars> package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class ModifyXmlFileDemo { public static void main(String argv[]) { try { File inputFile = new File("input.xml"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inputFile); Node cars = doc.getFirstChild(); Node supercar = doc.getElementsByTagName("supercars").item(0); // update supercar attribute NamedNodeMap attr = supercar.getAttributes(); Node nodeAttr = attr.getNamedItem("company"); nodeAttr.setTextContent("Lamborigini"); // loop the supercar child node NodeList list = supercar.getChildNodes(); for (int temp = 0; temp < list.getLength(); temp++) { Node node = list.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; if ("carname".equals(eElement.getNodeName())) { if("Ferrari 101".equals(eElement.getTextContent())) { eElement.setTextContent("Lamborigini 001"); } if("Ferrari 202".equals(eElement.getTextContent())) eElement.setTextContent("Lamborigini 002"); } } } NodeList childNodes = cars.getChildNodes(); for(int count = 0; count < childNodes.getLength(); count++) { Node node = childNodes.item(count); if("luxurycars".equals(node.getNodeName())) cars.removeChild(node); } // write the content on console TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); System.out.println("-----------Modified File-----------"); StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); } catch (Exception e) { e.printStackTrace(); } } } This would produce the following result − -----------Modified File----------- <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Lamborigini"> <carname type = "formula one">Lamborigini 001</carname> <carname type = "sports">Lamborigini 002</carname> </supercars> </cars> SAX (Simple API for XML) is an event-based parser for XML documents. Unlike a DOM parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML, which means that applications using SAX receive event notifications about the XML document being processed an element, and attribute, at a time in sequential order starting at the top of the document, and ending with the closing of the ROOT element. Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document. Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document. Tokens are processed in the same order that they appear in the document. Tokens are processed in the same order that they appear in the document. Reports the application program the nature of tokens that the parser has encountered as they occur. Reports the application program the nature of tokens that the parser has encountered as they occur. The application program provides an "event" handler that must be registered with the parser. The application program provides an "event" handler that must be registered with the parser. As the tokens are identified, callback methods in the handler are invoked with the relevant information. As the tokens are identified, callback methods in the handler are invoked with the relevant information. You should use a SAX parser when − You can process the XML document in a linear fashion from top to down. You can process the XML document in a linear fashion from top to down. The document is not deeply nested. The document is not deeply nested. You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML. You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML. The problem to be solved involves only a part of the XML document. The problem to be solved involves only a part of the XML document. Data is available as soon as it is seen by the parser, so SAX works well for an XML document that arrives over a stream. Data is available as soon as it is seen by the parser, so SAX works well for an XML document that arrives over a stream. We have no random access to an XML document since it is processed in a forward-only manner. We have no random access to an XML document since it is processed in a forward-only manner. If you need to keep track of data that the parser has seen or change the order of items, you must write the code and store the data on your own. If you need to keep track of data that the parser has seen or change the order of items, you must write the code and store the data on your own. This interface specifies the callback methods that the SAX parser uses to notify an application program of the components of the XML document that it has seen. void startDocument() − Called at the beginning of a document. void startDocument() − Called at the beginning of a document. void endDocument() − Called at the end of a document. void endDocument() − Called at the end of a document. void startElement(String uri, String localName, String qName, Attributes atts) − Called at the beginning of an element. void startElement(String uri, String localName, String qName, Attributes atts) − Called at the beginning of an element. void endElement(String uri, String localName,String qName) − Called at the end of an element. void endElement(String uri, String localName,String qName) − Called at the end of an element. void characters(char[] ch, int start, int length) − Called when character data is encountered. void characters(char[] ch, int start, int length) − Called when character data is encountered. void ignorableWhitespace( char[] ch, int start, int length) − Called when a DTD is present and ignorable whitespace is encountered. void ignorableWhitespace( char[] ch, int start, int length) − Called when a DTD is present and ignorable whitespace is encountered. void processingInstruction(String target, String data) − Called when a processing instruction is recognized. void processingInstruction(String target, String data) − Called when a processing instruction is recognized. void setDocumentLocator(Locator locator)) − Provides a Locator that can be used to identify positions in the document. void setDocumentLocator(Locator locator)) − Provides a Locator that can be used to identify positions in the document. void skippedEntity(String name) − Called when an unresolved entity is encountered. void skippedEntity(String name) − Called when an unresolved entity is encountered. void startPrefixMapping(String prefix, String uri) − Called when a new namespace mapping is defined. void startPrefixMapping(String prefix, String uri) − Called when a new namespace mapping is defined. void endPrefixMapping(String prefix) − Called when a namespace definition ends its scope. void endPrefixMapping(String prefix) − Called when a namespace definition ends its scope. This interface specifies methods for processing the attributes connected to an element. int getLength() − Returns number of attributes. int getLength() − Returns number of attributes. String getQName(int index) String getQName(int index) String getValue(int index) String getValue(int index) String getValue(String qname) String getValue(String qname) Here is the input xml file we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { String rollNo = attributes.getValue("rollno"); System.out.println("Roll No : " + rollNo); } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (bFirstName) { System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); UserHandler userhandler = new UserHandler(); saxParser.parse(inputFile, userhandler); } catch (Exception e) { e.printStackTrace(); } } } class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { String rollNo = attributes.getValue("rollno"); System.out.println("Roll No : " + rollNo); } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (bFirstName) { System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } This would produce the following result − Roll No : 393 First Name: dinkar Last Name: kad Nick Name: dinkar Marks: 85 End Element :student Roll No : 493 First Name: Vaneet Last Name: Gupta Nick Name: vinni Marks: 95 End Element :student Roll No : 593 First Name: jasvir Last Name: singn Nick Name: jazz Marks: 90 End Element :student Here is the input text file that we need to Query for rollno: 393 <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; String rollNo = null; @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { rollNo = attributes.getValue("rollno"); } if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) { System.out.println("Start Element :" + qName); } if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement( String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (bFirstName && ("393").equals(rollNo)) { //age element, set Employee age System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName && ("393").equals(rollNo)) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName && ("393").equals(rollNo)) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks && ("393").equals(rollNo)) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXQueryDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); UserHandler userhandler = new UserHandler(); saxParser.parse(inputFile, userhandler); } catch (Exception e) { e.printStackTrace(); } } } class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; String rollNo = null; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { rollNo = attributes.getValue("rollno"); } if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) { System.out.println("Start Element :" + qName); } if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement( String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) System.out.println("End Element :" + qName); } } @Override public void characters( char ch[], int start, int length) throws SAXException { if (bFirstName && ("393").equals(rollNo)) { //age element, set Employee age System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName && ("393").equals(rollNo)) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName && ("393").equals(rollNo)) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks && ("393").equals(rollNo)) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } This would produce the following result − Start Element :student First Name: dinkar Last Name: kad Nick Name: dinkar Marks: 85 End Element :student It is better to use StAX parser for creating XML documents rather than using SAX parser. Please refer the Java StAX Parser section for the same. Here is the input XML file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag. <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.*; import org.xml.sax.*; import javax.xml.parsers.*; import org.xml.sax.helpers.DefaultHandler; public class SAXModifyDemo extends DefaultHandler { static String displayText[] = new String[1000]; static int numberLines = 0; static String indentation = ""; public static void main(String args[]) { try { File inputFile = new File("input.txt"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXModifyDemo obj = new SAXModifyDemo(); obj.childLoop(inputFile); FileWriter filewriter = new FileWriter("newfile.xml"); for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) { filewriter.write(displayText[loopIndex].toCharArray()); filewriter.write('\n'); System.out.println(displayText[loopIndex].toString()); } filewriter.close(); } catch (Exception e) { e.printStackTrace(System.err); } } public void childLoop(File input) { DefaultHandler handler = this; SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(input, handler); } catch (Throwable t) {} } public void startDocument() { displayText[numberLines] = indentation; displayText[numberLines] += "<?xml version = \"1.0\" encoding = \""+ "UTF-8" + "\"?>"; numberLines++; } public void processingInstruction(String target, String data) { displayText[numberLines] = indentation; displayText[numberLines] += "<?"; displayText[numberLines] += target; if (data != null && data.length() > 0) { displayText[numberLines] += ' '; displayText[numberLines] += data; } displayText[numberLines] += "?>"; numberLines++; } public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) { displayText[numberLines] = indentation; indentation += " "; displayText[numberLines] += '<'; displayText[numberLines] += qualifiedName; if (attributes != null) { int numberAttributes = attributes.getLength(); for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) { displayText[numberLines] += ' '; displayText[numberLines] += attributes.getQName(loopIndex); displayText[numberLines] += "=\""; displayText[numberLines] += attributes.getValue(loopIndex); displayText[numberLines] += '"'; } } displayText[numberLines] += '>'; numberLines++; } public void characters(char characters[], int start, int length) { String characterData = (new String(characters, start, length)).trim(); if(characterData.indexOf("\n") < 0 && characterData.length() > 0) { displayText[numberLines] = indentation; displayText[numberLines] += characterData; numberLines++; } } public void endElement(String uri, String localName, String qualifiedName) { indentation = indentation.substring(0, indentation.length() - 4) ; displayText[numberLines] = indentation; displayText[numberLines] += "</"; displayText[numberLines] += qualifiedName; displayText[numberLines] += '>'; numberLines++; if (qualifiedName.equals("marks")) { startElement("", "Result", "Result", null); characters("Pass".toCharArray(), 0, "Pass".length()); endElement("", "Result", "Result"); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <class> <student rollno = "393"> <firstname> dinkar </firstname> <lastname> kad </lastname> <nickname> dinkar </nickname> <marks> 85 </marks> <Result> Pass </Result> </student> <student rollno = "493"> <firstname> Vaneet </firstname> <lastname> Gupta </lastname> <nickname> vinni </nickname> <marks> 95 </marks> <Result> Pass </Result> </student> <student rollno = "593"> <firstname> jasvir </firstname> <lastname> singn </lastname> <nickname> jazz </nickname> <marks> 90 </marks> <Result> Pass </Result> </student> </class> JDOM is an open source, Java-based library to parse XML documents. It is typically a Java developer friendly API. It is Java optimized and it uses Java collections like List and Arrays. JDOM works with DOM and SAX APIs and combines the best of the two. It is of low memory footprint and is nearly as fast as SAX. In order to use JDOM parser, you should have jdom.jar in your application's classpath. Download jdom-2.0.5.zip. You should use a JDOM parser when − You need to know a lot about the structure of an XML document. You need to know a lot about the structure of an XML document. You need to move parts of an XMl document around (you might want to sort certain elements, for example). You need to move parts of an XMl document around (you might want to sort certain elements, for example). You need to use the information in an XML document more than once. You need to use the information in an XML document more than once. You are a Java developer and want to leverage Java optimized parsing of XML. You are a Java developer and want to leverage Java optimized parsing of XML. When you parse an XML document with a JDOM parser, you get the flexibility to get back a tree structure that contains all of the elements of your document without impacting the memory footprint of the application. JDOM provides a variety of utility functions that you can use to examine the contents and structure of an XML document in case the document is well structured and its structure is known. JDOM provides Java developers the flexibility and easy maintainablity of XML parsing code. It is a lightweight and quick API. JDOM defines several Java classes. Here are the most common classes − Document − Represents an entire XML document. A Document object is often referred to as a DOM tree. Document − Represents an entire XML document. A Document object is often referred to as a DOM tree. Element − Represents an XML element. Element object has methods to manipulate its child elements, its text, attributes, and namespaces. Element − Represents an XML element. Element object has methods to manipulate its child elements, its text, attributes, and namespaces. Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type. Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type. Text − Represents the text of XML tag. Text − Represents the text of XML tag. Comment − Represents the comments in a XML document. Comment − Represents the comments in a XML document. When you are working with JDOM, there are several methods you'll use often − SAXBuilder.build(xmlSource)() − Build the JDOM document from the xml source. SAXBuilder.build(xmlSource)() − Build the JDOM document from the xml source. Document.getRootElement() − Get the root element of the XML. Document.getRootElement() − Get the root element of the XML. Element.getName() − Get the name of the XML node. Element.getName() − Get the name of the XML node. Element.getChildren() − Get all the direct child nodes of an element. Element.getChildren() − Get all the direct child nodes of an element. Node.getChildren(Name) − Get all the direct child nodes with a given name. Node.getChildren(Name) − Get all the direct child nodes with a given name. Node.getChild(Name) − Get the first child node with the given name. Node.getChild(Name) − Get the first child node with the given name. Following are the steps used while parsing a document using JDOM Parser. Import XML-related packages. Create a SAXBuilder Create a Document from a file or stream Extract the root element Examine attributes Examine sub-elements import java.io.*; import java.util.*; import org.jdom2.*; SAXBuilder saxBuilder = new SAXBuilder(); File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); Element classElement = document.getRootElement(); //returns specific attribute getAttribute("attributeName"); //returns a list of subelements of specified name getChildren("subelementName"); //returns a list of all child nodes getChildren(); //returns first child node getChild("subelementName"); Here is the input xml file we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class JDomParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Element> studentList = classElement.getChildren(); System.out.println("----------------------------"); for (int temp = 0; temp < studentList.size(); temp++) { Element student = studentList.get(temp); System.out.println("\nCurrent Element :" + student.getName()); Attribute attribute = student.getAttribute("rollno"); System.out.println("Student roll no : " + attribute.getValue() ); System.out.println("First Name : " + student.getChild("firstname").getText()); System.out.println("Last Name : " + student.getChild("lastname").getText()); System.out.println("Nick Name : " + student.getChild("nickname").getText()); System.out.println("Marks : " + student.getChild("marks").getText()); } } catch(JDOMException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } } This would produce the following result − Root element :class ---------------------------- Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singn Nick Name : jazz Marks : 90 Here is the input xml file that we need to query − <?xml version = "1.0"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferarri 101</carname> <carname type = "sports car">Ferarri 201</carname> <carname type = "sports car">Ferarri 301</carname> </supercars> <supercars company = "Lamborgini"> <carname>Lamborgini 001</carname> <carname>Lamborgini 002</carname> <carname>Lamborgini 003</carname> </supercars> <luxurycars company = "Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars> import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class QueryXmlFileDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Element> supercarList = classElement.getChildren("supercars"); System.out.println("----------------------------"); for (int temp = 0; temp < supercarList.size(); temp++) { Element supercarElement = supercarList.get(temp); System.out.println("\nCurrent Element :" + supercarElement.getName()); Attribute attribute = supercarElement.getAttribute("company"); System.out.println("company : " + attribute.getValue() ); List<Element> carNameList = supercarElement.getChildren("carname"); for (int count = 0; count < carNameList.size(); count++) { Element carElement = carNameList.get(count); System.out.print("car name : "); System.out.println(carElement.getText()); System.out.print("car type : "); Attribute typeAttribute = carElement.getAttribute("type"); if(typeAttribute != null) System.out.println(typeAttribute.getValue()); else { System.out.println(""); } } } } catch(JDOMException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } } This would produce the following result − Root element :cars ---------------------------- Current Element :supercars company : Ferrari car name : Ferarri 101 car type : formula one car name : Ferarri 201 car type : sports car car name : Ferarri 301 car type : sports car Current Element :supercars company : Lamborgini car name : Lamborgini 001 car type : car name : Lamborgini 002 car type : car name : Lamborgini 003 car type : Here is the XML file that we need to create − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> import java.io.IOException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class CreateXmlFileDemo { public static void main(String[] args) { try{ //root element Element carsElement = new Element("cars"); Document doc = new Document(carsElement); //supercars element Element supercarElement = new Element("supercars"); supercarElement.setAttribute(new Attribute("company","Ferrari")); //supercars element Element carElement1 = new Element("carname"); carElement1.setAttribute(new Attribute("type","formula one")); carElement1.setText("Ferrari 101"); Element carElement2 = new Element("carname"); carElement2.setAttribute(new Attribute("type","sports")); carElement2.setText("Ferrari 202"); supercarElement.addContent(carElement1); supercarElement.addContent(carElement2); doc.getRootElement().addContent(supercarElement); XMLOutputter xmlOutput = new XMLOutputter(); // display ml xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); } catch(IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> Here is the input text file that we need to modify − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> <luxurycars company = "Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars> import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class ModifyXMLFileDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); Element rootElement = document.getRootElement(); //get first supercar Element supercarElement = rootElement.getChild("supercars"); // update supercar attribute Attribute attribute = supercarElement.getAttribute("company"); attribute.setValue("Lamborigini"); // loop the supercar child node List<Element> list = supercarElement.getChildren(); for (int temp = 0; temp < list.size(); temp++) { Element carElement = list.get(temp); if("Ferrari 101".equals(carElement.getText())) { carElement.setText("Lamborigini 001"); } if("Ferrari 202".equals(carElement.getText())) { carElement.setText("Lamborigini 002"); } } //get all supercars element List<Element> supercarslist = rootElement.getChildren(); for (int temp = 0; temp < supercarslist.size(); temp++) { Element tempElement = supercarslist.get(temp); if("luxurycars".equals(tempElement.getName())) { rootElement.removeContent(tempElement); } } XMLOutputter xmlOutput = new XMLOutputter(); // display xml xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(document, System.out); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Lamborigini"> <carname type = "formula one">Lamborigini 001</carname> <carname type = "sports">Lamborigini 002</carname> </supercars> </cars> StAX is a Java-based API to parse XML document in a similar way as SAX parser does. But there are two major difference between the two APIs − StAX is a PULL API, whereas SAX is a PUSH API. It means in case of StAX parser, a client application needs to ask the StAX parser to get information from XML whenever it needs. But in case of SAX parser, a client application is required to get information when SAX parser notifies the client application that information is available. StAX is a PULL API, whereas SAX is a PUSH API. It means in case of StAX parser, a client application needs to ask the StAX parser to get information from XML whenever it needs. But in case of SAX parser, a client application is required to get information when SAX parser notifies the client application that information is available. StAX API can read as well as write XML documents. Using SAX API, an XML file can only be read. StAX API can read as well as write XML documents. Using SAX API, an XML file can only be read. In order to use StAX parser, you should have stax.jar in your application's classpath. Following are the features of StAX API − Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document. Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document. Tokens are processed in the same order that they appear in the document. Tokens are processed in the same order that they appear in the document. Reports the application program the nature of tokens that the parser has encountered as they occur. Reports the application program the nature of tokens that the parser has encountered as they occur. The application program provides an "event" reader which acts as an iterator and iterates over the event to get the required information. Another reader available is "cursor" which acts as a pointer to XML nodes. The application program provides an "event" reader which acts as an iterator and iterates over the event to get the required information. Another reader available is "cursor" which acts as a pointer to XML nodes. As the events are identified, XML elements can be retrieved from the event object and can be processed further. As the events are identified, XML elements can be retrieved from the event object and can be processed further. You should use a StAX parser when − You can process the XML document in a linear fashion from top to down. You can process the XML document in a linear fashion from top to down. The document is not deeply nested. The document is not deeply nested. You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML. You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML. The problem to be solved involves only a part of the XML document. The problem to be solved involves only a part of the XML document. Data is available as soon as it is seen by the parser, so StAX works well for an XML document that arrives over a stream. Data is available as soon as it is seen by the parser, so StAX works well for an XML document that arrives over a stream. We have no random access to an XML document, since it is processed in a forward-only manner. We have no random access to an XML document, since it is processed in a forward-only manner. If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own. If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own. This class provides iterator of events which can be used to iterate over events as they occur while parsing an XML document. StartElement asStartElement() − Used to retrieve the value and attributes of an element. StartElement asStartElement() − Used to retrieve the value and attributes of an element. EndElement asEndElement() − Called at the end of an element. EndElement asEndElement() − Called at the end of an element. Characters asCharacters() − Can be used to obtain characters such as CDATA, whitespace, etc. Characters asCharacters() − Can be used to obtain characters such as CDATA, whitespace, etc. This interface specifies methods for creating an event. add(Event event) − Add event containing elements to XML. add(Event event) − Add event containing elements to XML. This class provides iterator of events which can be used to iterate over events as they occur while parsing an XML document. int next() − Used to retrieve next event. int next() − Used to retrieve next event. boolean hasNext() − Used to check further events exists or not. boolean hasNext() − Used to check further events exists or not. String getText() − Used to get text of an element. String getText() − Used to get text of an element. String getLocalName() − Used to get name of an element. String getLocalName() − Used to get name of an element. This interface specifies methods for creating an event. writeStartElement(String localName) − Add a start element of given name. writeStartElement(String localName) − Add a start element of given name. writeEndElement(String localName) − Add an end element of given name. writeEndElement(String localName) − Add an end element of given name. writeAttribute(String localName, String value) − Write attributes to an element. writeAttribute(String localName, String value) − Write attributes to an element. Here is the input xml file that we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Iterator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class StAXParserDemo { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("input.txt")); while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); if (qName.equalsIgnoreCase("student")) { System.out.println("Start Element : student"); Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); System.out.println("Roll No : " + rollNo); } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); if(bFirstName) { System.out.println("First Name: " + characters.getData()); bFirstName = false; } if(bLastName) { System.out.println("Last Name: " + characters.getData()); bLastName = false; } if(bNickName) { System.out.println("Nick Name: " + characters.getData()); bNickName = false; } if(bMarks) { System.out.println("Marks: " + characters.getData()); bMarks = false; } break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); if(endElement.getName().getLocalPart().equalsIgnoreCase("student")) { System.out.println("End Element : student"); System.out.println(); } break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } } } This would produce the following result − Start Element : student Roll No : 393 First Name: dinkar Last Name: kad Nick Name: dinkar Marks: 85 End Element : student Start Element : student Roll No : 493 First Name: Vaneet Last Name: Gupta Nick Name: vinni Marks: 95 End Element : student Start Element : student Roll No : 593 First Name: jasvir Last Name: singn Nick Name: jazz Marks: 90 End Element : student Here is the input xml file that we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Iterator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class StAXQueryDemo { public static void main(String[] args) { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; boolean isRequestRollNo = false; try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("input.txt")); String requestedRollNo = "393"; while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); if (qName.equalsIgnoreCase("student")) { Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); if(rollNo.equalsIgnoreCase(requestedRollNo)) { System.out.println("Start Element : student"); System.out.println("Roll No : " + rollNo); isRequestRollNo = true; } } else if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); if(bFirstName && isRequestRollNo) { System.out.println("First Name: " + characters.getData()); bFirstName = false; } if(bLastName && isRequestRollNo) { System.out.println("Last Name: " + characters.getData()); bLastName = false; } if(bNickName && isRequestRollNo) { System.out.println("Nick Name: " + characters.getData()); bNickName = false; } if(bMarks && isRequestRollNo) { System.out.println("Marks: " + characters.getData()); bMarks = false; } break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); if(endElement.getName().getLocalPart().equalsIgnoreCase( "student") && isRequestRollNo) { System.out.println("End Element : student"); System.out.println(); isRequestRollNo = false; } break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } } } This would produce the following result − Start Element : student Roll No : 393 First Name: dinkar Last Name: kad Nick Name: dinkar Marks: 85 End Element : student Here is the XML that we need to create − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> package com.tutorialspoint.xml; import java.io.IOException; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class StAXCreateXMLDemo { public static void main(String[] args) { try { StringWriter stringWriter = new StringWriter(); XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xMLStreamWriter = xMLOutputFactory.createXMLStreamWriter(stringWriter); xMLStreamWriter.writeStartDocument(); xMLStreamWriter.writeStartElement("cars"); xMLStreamWriter.writeStartElement("supercars"); xMLStreamWriter.writeAttribute("company", "Ferrari"); xMLStreamWriter.writeStartElement("carname"); xMLStreamWriter.writeAttribute("type", "formula one"); xMLStreamWriter.writeCharacters("Ferrari 101"); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeStartElement("carname"); xMLStreamWriter.writeAttribute("type", "sports"); xMLStreamWriter.writeCharacters("Ferrari 202"); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndElement(); xMLStreamWriter.writeEndDocument(); xMLStreamWriter.flush(); xMLStreamWriter.close(); String xmlString = stringWriter.getBuffer().toString(); stringWriter.close(); System.out.println(xmlString); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> Here is the XML that we need to modify − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class StAXModifyDemo { public static void main(String[] args) { try { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader( new FileReader("input.txt")); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(new File("input.txt")); Element rootElement = document.getRootElement(); List<Element> studentElements = rootElement.getChildren("student"); while(eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); if (qName.equalsIgnoreCase("student")) { Iterator<Attribute> attributes = startElement.getAttributes(); String rollNo = attributes.next().getValue(); if(rollNo.equalsIgnoreCase("393")) { //get the student with roll no 393 for(int i = 0;i < studentElements.size();i++) { Element studentElement = studentElements.get(i); if(studentElement.getAttribute( "rollno").getValue().equalsIgnoreCase("393")) { studentElement.removeChild("marks"); studentElement.addContent(new Element("marks").setText("80")); } } } } break; } } XMLOutputter xmlOutput = new XMLOutputter(); // display xml xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(document, System.out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>80</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> XPath is an official recommendation of the World Wide Web Consortium (W3C). It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document. Structure Definations − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes. Structure Definations − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes. Path Expressions − XPath provides powerful path expressions such as select nodes or list of nodes in XML documents. Path Expressions − XPath provides powerful path expressions such as select nodes or list of nodes in XML documents. Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, etc. Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, etc. Major part of XSLT − XPath is one of the major elements in XSLT standard and one must have sufficient knowledge of XPath in order to work with XSLT documents. Major part of XSLT − XPath is one of the major elements in XSLT standard and one must have sufficient knowledge of XPath in order to work with XSLT documents. W3C recommendation − XPath is official recommendation of World Wide Web Consortium (W3C). W3C recommendation − XPath is official recommendation of World Wide Web Consortium (W3C). XPath uses a path expression to select node or list of nodes from an XML document. Following is a list of useful paths and expression to select any node/list of nodes from an XML document. node-name Select all nodes with the given name "nodename" / Selection starts from the root node // Selection starts from the current node that match the selection . Selects the current node .. Selects the parent of the current node @ Selects attributes student Example − Selects all nodes with the name "student" class/student Example − Selects all student elements that are children of class //student Selects all student elements no matter where they are in the document Predicates are used to find specific node or a node containing specific value and are defined using [...]. Following are the steps used while parsing a document using XPath Parser. Import XML-related packages. Import XML-related packages. Create a DocumentBuilder. Create a DocumentBuilder. Create a Document from a file or stream. Create a Document from a file or stream. Create an Xpath object and an XPath path expression. Create an Xpath object and an XPath path expression. Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate(). Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate(). Iterate over the list of nodes. Iterate over the list of nodes. Examine attributes. Examine attributes. Examine sub-elements. Examine sub-elements. import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; import javax.xml.xpath.*; import java.io.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuilder xmlStringBuilder = new StringBuilder(); xmlStringBuilder.append("<?xml version = "1.0"?> <class> </class>"); ByteArrayInputStream input = new ByteArrayInputStream( xmlStringBuilder.toString().getBytes("UTF-8")); Document doc = builder.parse(input); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/class/student"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); ... } //returns specific attribute getAttribute("attributeName"); //returns a Map (table) of names/values getAttributes(); //returns a list of subelements of specified name getElementsByTagName("subelementName"); //returns a list of all child nodes getChildNodes(); Here is the input text file we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singh</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.xml.sax.SAXException; public class XPathParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/class/student"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Student roll no :" + eElement.getAttribute("rollno")); System.out.println("First Name : " + eElement .getElementsByTagName("firstname") .item(0) .getTextContent()); System.out.println("Last Name : " + eElement .getElementsByTagName("lastname") .item(0) .getTextContent()); System.out.println("Nick Name : " + eElement .getElementsByTagName("nickname") .item(0) .getTextContent()); System.out.println("Marks : " + eElement .getElementsByTagName("marks") .item(0) .getTextContent()); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } } This would produce the following result − Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singh Nick Name : jazz Marks : 90 Here is the input text file that we need to query − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.xml.sax.SAXException; public class XPathParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/class/student[@rollno = '493']"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate( doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node nNode = nodeList.item(i); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Student roll no : " + eElement.getAttribute("rollno")); System.out.println("First Name : " + eElement .getElementsByTagName("firstname") .item(0) .getTextContent()); System.out.println("Last Name : " + eElement .getElementsByTagName("lastname") .item(0) .getTextContent()); System.out.println("Nick Name : " + eElement .getElementsByTagName("nickname") .item(0) .getTextContent()); System.out.println("Marks : " + eElement .getElementsByTagName("marks") .item(0) .getTextContent()); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } } This would produce the following result − Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 XPath parser is used to navigate XML Documents only. It is better to use DOM parser for creating XML. Please refer the Java DOM Parser section for the same. XPath parser is used to navigate XML Documents only. It is better to use DOM parser for modifying XML. Please refer the Java DOM Parser section for the same. DOM4J is an open source, Java-based library to parse XML documents. It is a highly flexible and memory-efficient API. It is Java-optimized and uses Java collections like List and Arrays. DOM4J works with DOM, SAX, XPath, and XSLT. It can parse large XML documents with very low memory footprint. In order to use DOM4J parser, you should have dom4j-1.6.1.jar and jaxen.jar in your application's classpath. Download dom4j-1.6.1.zip. You should use a DOM4J parser when − You need to know a lot about the structure of an XML document. You need to know a lot about the structure of an XML document. You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to move parts of an XML document around (you might want to sort certain elements, for example). You need to use the information in an XML document more than once. You need to use the information in an XML document more than once. You are a Java developer and want to leverage Java-optimized parsing of XML. You are a Java developer and want to leverage Java-optimized parsing of XML. When you parse an XML document with a DOM4J parser, you get the flexibility to get back a tree structure that contains all of the elements of your document without impacting the memory footprint of the application. DOM4J provides a variety of utility functions that you can use to examine the contents and structure of an XML document in case the document is well structured and its structure is known. DOM4J uses XPath expression to navigate through an XML document. DOM4J provides Java developers the flexibility and easy maintainablity of XML parsing code. It is a lightweight and quick API. DOM4J defines several Java classes. Here are the most common classes − Document − Represents the entire XML document. A Document object is often referred to as a DOM tree. Document − Represents the entire XML document. A Document object is often referred to as a DOM tree. Element − Represents an XML element. Element object has methods to manipulate its child elements, text, attributes, and namespaces. Element − Represents an XML element. Element object has methods to manipulate its child elements, text, attributes, and namespaces. Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type. Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type. Node − Represents Element, Attribute, or ProcessingInstruction. Node − Represents Element, Attribute, or ProcessingInstruction. When you are working with the DOM4J, there are several methods you'll use often − SAXReader.read(xmlSource)() − Build the DOM4J document from an XML source. SAXReader.read(xmlSource)() − Build the DOM4J document from an XML source. Document.getRootElement() − Get the root element of an XML document. Document.getRootElement() − Get the root element of an XML document. Element.node(index) − Get the XML node at a particular index in an element. Element.node(index) − Get the XML node at a particular index in an element. Element.attributes() − Get all the attributes of an element. Element.attributes() − Get all the attributes of an element. Node.valueOf(@Name) − Get the values of an attribute with the given name of an element. Node.valueOf(@Name) − Get the values of an attribute with the given name of an element. Following are the steps used while parsing a document using DOM4J Parser. Import XML-related packages. Import XML-related packages. Create a SAXReader. Create a SAXReader. Create a Document from a file or stream. Create a Document from a file or stream. Get the required nodes using XPath Expression by calling document.selectNodes() Get the required nodes using XPath Expression by calling document.selectNodes() Extract the root element. Extract the root element. Iterate over the list of nodes. Iterate over the list of nodes. Examine attributes. Examine attributes. Examine sub-elements. Examine sub-elements. import java.io.*; import java.util.*; import org.dom4j.*; SAXBuilder saxBuilder = new SAXBuilder(); File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); Element classElement = document.getRootElement(); //returns specific attribute valueOf("@attributeName"); //returns first child node selectSingleNode("subelementName"); Here is the input xml file that we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class DOM4JParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXReader reader = new SAXReader(); Document document = reader.read( inputFile ); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Node> nodes = document.selectNodes("/class/student" ); System.out.println("----------------------------"); for (Node node : nodes) { System.out.println("\nCurrent Element :" + node.getName()); System.out.println("Student roll no : " + node.valueOf("@rollno") ); System.out.println("First Name : " + node.selectSingleNode("firstname").getText()); System.out.println("Last Name : " + node.selectSingleNode("lastname").getText()); System.out.println("First Name : " + node.selectSingleNode("nickname").getText()); System.out.println("Marks : " + node.selectSingleNode("marks").getText()); } } catch (DocumentException e) { e.printStackTrace(); } } } This would produce the following result − Root element :class ---------------------------- Current Element :student Student roll no : First Name : dinkar Last Name : kad First Name : dinkar Marks : 85 Current Element :student Student roll no : First Name : Vaneet Last Name : Gupta First Name : vinni Marks : 95 Current Element :student Student roll no : First Name : jasvir Last Name : singn First Name : jazz Marks : 90 Here is the input xml file that we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; public class DOM4JQueryDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXReader reader = new SAXReader(); Document document = reader.read( inputFile ); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Node> nodes = document.selectNodes("/class/student[@rollno = '493']" ); System.out.println("----------------------------"); for (Node node : nodes) { System.out.println("\nCurrent Element :" + node.getName()); System.out.println("Student roll no : " + node.valueOf("@rollno") ); System.out.println("First Name : " + node.selectSingleNode("firstname").getText()); System.out.println("Last Name : " + node.selectSingleNode("lastname").getText()); System.out.println("First Name : " + node.selectSingleNode("nickname").getText()); System.out.println("Marks : " + node.selectSingleNode("marks").getText()); } } catch (DocumentException e) { e.printStackTrace(); } } } This would produce the following result − Root element :class ---------------------------- Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta First Name : vinni Marks : 95 Here is the XML that we need to create − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> package com.tutorialspoint.xml; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class DOM4JCreateXMLDemo { public static void main(String[] args) { try { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "cars" ); Element supercarElement = root.addElement("supercars") .addAttribute("company", "Ferrai"); supercarElement.addElement("carname") .addAttribute("type", "Ferrari 101") .addText("Ferrari 101"); supercarElement.addElement("carname") .addAttribute("type", "sports") .addText("Ferrari 202"); // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer; writer = new XMLWriter( System.out, format ); writer.write( document ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> Here is the XML that we need to modify − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class DOM4jModifyXMLDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXReader reader = new SAXReader(); Document document = reader.read( inputFile ); Element classElement = document.getRootElement(); List<Node> nodes = document.selectNodes("/class/student[@rollno = '493']" ); for (Node node : nodes) { Element element = (Element)node; Iterator<Element> iterator = element.elementIterator("marks"); while(iterator.hasNext()) { Element marksElement = (Element)iterator.next(); marksElement.setText("80"); } } // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer; writer = new XMLWriter( System.out, format ); writer.write( document ); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>80</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> 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": 2323, "text": "XML is a simple text-based language which was designed to store and transport data in plain text format. It stands for Extensible Markup Language. Following are some of the salient features of XML." }, { "code": null, "e": 2547, "s": 2521, "text": "XML is a markup language." }, { "code": null, "e": 2573, "s": 2547, "text": "XML is a markup language." }, { "code": null, "e": 2612, "s": 2573, "text": "XML is a tag based language like HTML." }, { "code": null, "e": 2651, "s": 2612, "text": "XML is a tag based language like HTML." }, { "code": null, "e": 2690, "s": 2651, "text": "XML tags are not predefined like HTML." }, { "code": null, "e": 2729, "s": 2690, "text": "XML tags are not predefined like HTML." }, { "code": null, "e": 2805, "s": 2729, "text": "You can define your own tags which is why it is called extensible language." }, { "code": null, "e": 2881, "s": 2805, "text": "You can define your own tags which is why it is called extensible language." }, { "code": null, "e": 2927, "s": 2881, "text": "XML tags are designed to be self-descriptive." }, { "code": null, "e": 2973, "s": 2927, "text": "XML tags are designed to be self-descriptive." }, { "code": null, "e": 3035, "s": 2973, "text": "XML is W3C Recommendation for data storage and data transfer." }, { "code": null, "e": 3097, "s": 3035, "text": "XML is W3C Recommendation for data storage and data transfer." }, { "code": null, "e": 3728, "s": 3097, "text": "<?xml version = \"1.0\"?>\n<Class>\n <Name>First</Name>\n <Sections>\n <Section>\n <Name>A</Name>\n <Students>\n <Student>Rohan</Student>\n <Student>Mohan</Student>\n <Student>Sohan</Student>\n <Student>Lalit</Student>\n <Student>Vinay</Student>\n </Students>\n </Section>\n \n <Section>\n <Name>B</Name>\n <Students>\n <Student>Robert</Student>\n <Student>Julie</Student>\n <Student>Kalie</Student>\n <Student>Michael</Student>\n </Students>\n </Section>\n </Sections>\n</Class>" }, { "code": null, "e": 3777, "s": 3728, "text": "Following are the advantages that XML provides −" }, { "code": null, "e": 3925, "s": 3777, "text": "Technology agnostic − Being plain text, XML is technology independent. It can be used by any technology for data storage and data transfer purpose." }, { "code": null, "e": 4073, "s": 3925, "text": "Technology agnostic − Being plain text, XML is technology independent. It can be used by any technology for data storage and data transfer purpose." }, { "code": null, "e": 4160, "s": 4073, "text": "Human readable − XML uses simple text format. It is human readable and understandable." }, { "code": null, "e": 4247, "s": 4160, "text": "Human readable − XML uses simple text format. It is human readable and understandable." }, { "code": null, "e": 4317, "s": 4247, "text": "Extensible − In XML, custom tags can be created and used very easily." }, { "code": null, "e": 4387, "s": 4317, "text": "Extensible − In XML, custom tags can be created and used very easily." }, { "code": null, "e": 4465, "s": 4387, "text": "Allow Validation − Using XSD, DTD and XML structures can be validated easily." }, { "code": null, "e": 4543, "s": 4465, "text": "Allow Validation − Using XSD, DTD and XML structures can be validated easily." }, { "code": null, "e": 4590, "s": 4543, "text": "Following are the disadvantages of using XML −" }, { "code": null, "e": 4663, "s": 4590, "text": "Redundant Syntax − Normally XML files contain a lot of repetitive terms." }, { "code": null, "e": 4736, "s": 4663, "text": "Redundant Syntax − Normally XML files contain a lot of repetitive terms." }, { "code": null, "e": 4832, "s": 4736, "text": "Verbose − Being a verbose language, XML file size increases the transmission and storage costs." }, { "code": null, "e": 4928, "s": 4832, "text": "Verbose − Being a verbose language, XML file size increases the transmission and storage costs." }, { "code": null, "e": 5015, "s": 4928, "text": "XML Parsing refers to going through an XML document in order to access or modify data." }, { "code": null, "e": 5232, "s": 5015, "text": "XML Parser provides a way to access or modify data in an XML document. Java provides multiple options to parse XML documents. Following are the various types of parsers which are commonly used to parse XML documents." }, { "code": null, "e": 5372, "s": 5232, "text": "Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory." }, { "code": null, "e": 5512, "s": 5372, "text": "Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory." }, { "code": null, "e": 5626, "s": 5512, "text": "SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory." }, { "code": null, "e": 5740, "s": 5626, "text": "SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory." }, { "code": null, "e": 5834, "s": 5740, "text": "JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way." }, { "code": null, "e": 5928, "s": 5834, "text": "JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way." }, { "code": null, "e": 6029, "s": 5928, "text": "StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way." }, { "code": null, "e": 6130, "s": 6029, "text": "StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way." }, { "code": null, "e": 6238, "s": 6130, "text": "XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT." }, { "code": null, "e": 6346, "s": 6238, "text": "XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT." }, { "code": null, "e": 6484, "s": 6346, "text": "DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP." }, { "code": null, "e": 6622, "s": 6484, "text": "DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP." }, { "code": null, "e": 6790, "s": 6622, "text": "There are JAXB and XSLT APIs available to handle XML parsing in object-oriented way. We'll elaborate each parser in detail in the subsequent chapters of this tutorial." }, { "code": null, "e": 7067, "s": 6790, "text": "The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). It defines an interface that enables programs to access and update the style, structure, and contents of XML documents. XML parsers that support DOM implement this interface." }, { "code": null, "e": 7102, "s": 7067, "text": "You should use a DOM parser when −" }, { "code": null, "e": 7160, "s": 7102, "text": "You need to know a lot about the structure of a document." }, { "code": null, "e": 7218, "s": 7160, "text": "You need to know a lot about the structure of a document." }, { "code": null, "e": 7323, "s": 7218, "text": "You need to move parts of an XML document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 7428, "s": 7323, "text": "You need to move parts of an XML document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 7495, "s": 7428, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 7562, "s": 7495, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 7801, "s": 7562, "text": "When you parse an XML document with a DOM parser, you get back a tree structure that contains all of the elements of your document. The DOM provides a variety of functions you can use to examine the contents and structure of the document." }, { "code": null, "e": 8033, "s": 7801, "text": "The DOM is a common interface for manipulating document structures. One of its design goals is that Java code written for one DOM-compliant parser should run on any other DOM-compliant parser without having to do any modifications." }, { "code": null, "e": 8112, "s": 8033, "text": "The DOM defines several Java interfaces. Here are the most common interfaces −" }, { "code": null, "e": 8149, "s": 8112, "text": "Node − The base datatype of the DOM." }, { "code": null, "e": 8186, "s": 8149, "text": "Node − The base datatype of the DOM." }, { "code": null, "e": 8260, "s": 8186, "text": "Element − The vast majority of the objects you'll deal with are Elements." }, { "code": null, "e": 8334, "s": 8260, "text": "Element − The vast majority of the objects you'll deal with are Elements." }, { "code": null, "e": 8380, "s": 8334, "text": "Attr − Represents an attribute of an element." }, { "code": null, "e": 8426, "s": 8380, "text": "Attr − Represents an attribute of an element." }, { "code": null, "e": 8475, "s": 8426, "text": "Text − The actual content of an Element or Attr." }, { "code": null, "e": 8524, "s": 8475, "text": "Text − The actual content of an Element or Attr." }, { "code": null, "e": 8625, "s": 8524, "text": "Document − Represents the entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 8726, "s": 8625, "text": "Document − Represents the entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 8802, "s": 8726, "text": "When you are working with DOM, there are several methods you'll use often −" }, { "code": null, "e": 8876, "s": 8802, "text": "Document.getDocumentElement() − Returns the root element of the document." }, { "code": null, "e": 8950, "s": 8876, "text": "Document.getDocumentElement() − Returns the root element of the document." }, { "code": null, "e": 9014, "s": 8950, "text": "Node.getFirstChild() − Returns the first child of a given Node." }, { "code": null, "e": 9078, "s": 9014, "text": "Node.getFirstChild() − Returns the first child of a given Node." }, { "code": null, "e": 9140, "s": 9078, "text": "Node.getLastChild() − Returns the last child of a given Node." }, { "code": null, "e": 9202, "s": 9140, "text": "Node.getLastChild() − Returns the last child of a given Node." }, { "code": null, "e": 9281, "s": 9202, "text": "Node.getNextSibling() − These methods return the next sibling of a given Node." }, { "code": null, "e": 9360, "s": 9281, "text": "Node.getNextSibling() − These methods return the next sibling of a given Node." }, { "code": null, "e": 9447, "s": 9360, "text": "Node.getPreviousSibling() − These methods return the previous sibling of a given Node." }, { "code": null, "e": 9534, "s": 9447, "text": "Node.getPreviousSibling() − These methods return the previous sibling of a given Node." }, { "code": null, "e": 9632, "s": 9534, "text": "Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name." }, { "code": null, "e": 9730, "s": 9632, "text": "Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name." }, { "code": null, "e": 9803, "s": 9730, "text": "Following are the steps used while parsing a document using JDOM Parser." }, { "code": null, "e": 9832, "s": 9803, "text": "Import XML-related packages." }, { "code": null, "e": 9857, "s": 9832, "text": "Create a DocumentBuilder" }, { "code": null, "e": 9897, "s": 9857, "text": "Create a Document from a file or stream" }, { "code": null, "e": 9922, "s": 9897, "text": "Extract the root element" }, { "code": null, "e": 9941, "s": 9922, "text": "Examine attributes" }, { "code": null, "e": 9962, "s": 9941, "text": "Examine sub-elements" }, { "code": null, "e": 10030, "s": 9962, "text": "import org.w3c.dom.*;\nimport javax.xml.parsers.*;\nimport java.io.*;" }, { "code": null, "e": 10157, "s": 10030, "text": "DocumentBuilderFactory factory =\nDocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();" }, { "code": null, "e": 10406, "s": 10157, "text": "StringBuilder xmlStringBuilder = new StringBuilder();\nxmlStringBuilder.append(\"<?xml version=\"1.0\"?> \");\nByteArrayInputStream input = new ByteArrayInputStream(\n xmlStringBuilder.toString().getBytes(\"UTF-8\"));\nDocument doc = builder.parse(input);" }, { "code": null, "e": 10452, "s": 10406, "text": "Element root = document.getDocumentElement();" }, { "code": null, "e": 10570, "s": 10452, "text": "//returns specific attribute\ngetAttribute(\"attributeName\");\n\n//returns a Map (table) of names/values\ngetAttributes();" }, { "code": null, "e": 10714, "s": 10570, "text": "//returns a list of subelements of specified name\ngetElementsByTagName(\"subelementName\");\n\n//returns a list of all child nodes\ngetChildNodes();" }, { "code": null, "e": 10765, "s": 10714, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 11316, "s": 10765, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 13476, "s": 11316, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Element;\n\npublic class DomParserDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputFile);\n doc.getDocumentElement().normalize();\n System.out.println(\"Root element :\" + doc.getDocumentElement().getNodeName());\n NodeList nList = doc.getElementsByTagName(\"student\");\n System.out.println(\"----------------------------\");\n \n for (int temp = 0; temp < nList.getLength(); temp++) {\n Node nNode = nList.item(temp);\n System.out.println(\"\\nCurrent Element :\" + nNode.getNodeName());\n \n if (nNode.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) nNode;\n System.out.println(\"Student roll no : \" \n + eElement.getAttribute(\"rollno\"));\n System.out.println(\"First Name : \" \n + eElement\n .getElementsByTagName(\"firstname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Last Name : \" \n + eElement\n .getElementsByTagName(\"lastname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Nick Name : \" \n + eElement\n .getElementsByTagName(\"nickname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Marks : \" \n + eElement\n .getElementsByTagName(\"marks\")\n .item(0)\n .getTextContent());\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 13518, "s": 13476, "text": "This would produce the following result −" }, { "code": null, "e": 13911, "s": 13518, "text": "Root element :class\n----------------------------\n\nCurrent Element :student\nStudent roll no : 393\nFirst Name : dinkar\nLast Name : kad\nNick Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : 593\nFirst Name : jasvir\nLast Name : singn\nNick Name : jazz\nMarks : 90\n" }, { "code": null, "e": 13962, "s": 13911, "text": "Here is the input xml file that we need to query −" }, { "code": null, "e": 14568, "s": 13962, "text": "<?xml version = \"1.0\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferarri 101</carname>\n <carname type = \"sports car\">Ferarri 201</carname>\n <carname type = \"sports car\">Ferarri 301</carname>\n </supercars>\n \n <supercars company = \"Lamborgini\">\n <carname>Lamborgini 001</carname>\n <carname>Lamborgini 002</carname>\n <carname>Lamborgini 003</carname>\n </supercars>\n \n <luxurycars company = \"Benteley\">\n <carname>Benteley 1</carname>\n <carname>Benteley 2</carname>\n <carname>Benteley 3</carname>\n </luxurycars>\n</cars>" }, { "code": null, "e": 16660, "s": 14568, "text": "package com.tutorialspoint.xml;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Element;\nimport java.io.File;\n\npublic class QueryXmlFileDemo {\n\n public static void main(String argv[]) {\n \n try {\n File inputFile = new File(\"input.txt\");\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(inputFile);\n doc.getDocumentElement().normalize();\n System.out.print(\"Root element: \");\n System.out.println(doc.getDocumentElement().getNodeName());\n NodeList nList = doc.getElementsByTagName(\"supercars\");\n System.out.println(\"----------------------------\");\n \n for (int temp = 0; temp < nList.getLength(); temp++) {\n Node nNode = nList.item(temp);\n System.out.println(\"\\nCurrent Element :\");\n System.out.print(nNode.getNodeName());\n \n if (nNode.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) nNode;\n System.out.print(\"company : \");\n System.out.println(eElement.getAttribute(\"company\"));\n NodeList carNameList = eElement.getElementsByTagName(\"carname\");\n \n for (int count = 0; count < carNameList.getLength(); count++) {\n Node node1 = carNameList.item(count);\n \n if (node1.getNodeType() == node1.ELEMENT_NODE) {\n Element car = (Element) node1;\n System.out.print(\"car name : \");\n System.out.println(car.getTextContent());\n System.out.print(\"car type : \");\n System.out.println(car.getAttribute(\"type\"));\n }\n }\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 16702, "s": 16660, "text": "This would produce the following result −" }, { "code": null, "e": 17096, "s": 16702, "text": "Root element: cars\n----------------------------\n\nCurrent Element :\nsupercarscompany : Ferrari\ncar name : Ferarri 101\ncar type : formula one\ncar name : Ferarri 201\ncar type : sports car\ncar name : Ferarri 301\ncar type : sports car\n\nCurrent Element :\nsupercarscompany : Lamborgini\ncar name : Lamborgini 001\ncar type : \ncar name : Lamborgini 002\ncar type : \ncar name : Lamborgini 003\ncar type : \n" }, { "code": null, "e": 17132, "s": 17096, "text": "Here is the XML we need to create −" }, { "code": null, "e": 17370, "s": 17132, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 19773, "s": 17370, "text": "package com.tutorialspoint.xml;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\nimport org.w3c.dom.Attr;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport java.io.File;\n\npublic class CreateXmlFileDemo {\n\n public static void main(String argv[]) {\n\n try {\n DocumentBuilderFactory dbFactory =\n DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.newDocument();\n \n // root element\n Element rootElement = doc.createElement(\"cars\");\n doc.appendChild(rootElement);\n\n // supercars element\n Element supercar = doc.createElement(\"supercars\");\n rootElement.appendChild(supercar);\n\n // setting attribute to element\n Attr attr = doc.createAttribute(\"company\");\n attr.setValue(\"Ferrari\");\n supercar.setAttributeNode(attr);\n\n // carname element\n Element carname = doc.createElement(\"carname\");\n Attr attrType = doc.createAttribute(\"type\");\n attrType.setValue(\"formula one\");\n carname.setAttributeNode(attrType);\n carname.appendChild(doc.createTextNode(\"Ferrari 101\"));\n supercar.appendChild(carname);\n\n Element carname1 = doc.createElement(\"carname\");\n Attr attrType1 = doc.createAttribute(\"type\");\n attrType1.setValue(\"sports\");\n carname1.setAttributeNode(attrType1);\n carname1.appendChild(doc.createTextNode(\"Ferrari 202\"));\n supercar.appendChild(carname1);\n\n // write the content into xml file\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n DOMSource source = new DOMSource(doc);\n StreamResult result = new StreamResult(new File(\"C:\\\\cars.xml\"));\n transformer.transform(source, result);\n \n // Output to console for testing\n StreamResult consoleResult = new StreamResult(System.out);\n transformer.transform(source, consoleResult);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 19815, "s": 19773, "text": "This would produce the following result −" }, { "code": null, "e": 20055, "s": 19815, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 20102, "s": 20055, "text": "Here is the input xml file we need to modify −" }, { "code": null, "e": 20506, "s": 20102, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n \n <luxurycars company = \"Benteley\">\n <carname>Benteley 1</carname>\n <carname>Benteley 2</carname>\n <carname>Benteley 3</carname>\n </luxurycars>\n</cars>" }, { "code": null, "e": 23166, "s": 20506, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\n\npublic class ModifyXmlFileDemo {\n\n public static void main(String argv[]) {\n\n try {\n File inputFile = new File(\"input.xml\");\n DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder docBuilder = docFactory.newDocumentBuilder();\n Document doc = docBuilder.parse(inputFile);\n Node cars = doc.getFirstChild();\n Node supercar = doc.getElementsByTagName(\"supercars\").item(0);\n \n // update supercar attribute\n NamedNodeMap attr = supercar.getAttributes();\n Node nodeAttr = attr.getNamedItem(\"company\");\n nodeAttr.setTextContent(\"Lamborigini\");\n\n // loop the supercar child node\n NodeList list = supercar.getChildNodes();\n \n for (int temp = 0; temp < list.getLength(); temp++) {\n Node node = list.item(temp);\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) node;\n if (\"carname\".equals(eElement.getNodeName())) {\n if(\"Ferrari 101\".equals(eElement.getTextContent())) {\n eElement.setTextContent(\"Lamborigini 001\");\n }\n if(\"Ferrari 202\".equals(eElement.getTextContent()))\n eElement.setTextContent(\"Lamborigini 002\");\n }\n }\n }\n NodeList childNodes = cars.getChildNodes();\n \n for(int count = 0; count < childNodes.getLength(); count++) {\n Node node = childNodes.item(count);\n \n if(\"luxurycars\".equals(node.getNodeName()))\n cars.removeChild(node);\n }\n\n // write the content on console\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n DOMSource source = new DOMSource(doc);\n System.out.println(\"-----------Modified File-----------\");\n StreamResult consoleResult = new StreamResult(System.out);\n transformer.transform(source, consoleResult);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 23208, "s": 23166, "text": "This would produce the following result −" }, { "code": null, "e": 23497, "s": 23208, "text": "-----------Modified File-----------\n<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n\n<cars>\n <supercars company = \"Lamborigini\">\n <carname type = \"formula one\">Lamborigini 001</carname>\n <carname type = \"sports\">Lamborigini 002</carname>\n </supercars>\n</cars> \n" }, { "code": null, "e": 23911, "s": 23497, "text": "SAX (Simple API for XML) is an event-based parser for XML documents. Unlike a DOM parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML, which means that applications using SAX receive event notifications about the XML document being processed an element, and attribute, at a time in sequential order starting at the top of the document, and ending with the closing of the ROOT element." }, { "code": null, "e": 24017, "s": 23911, "text": "Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document." }, { "code": null, "e": 24123, "s": 24017, "text": "Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document." }, { "code": null, "e": 24196, "s": 24123, "text": "Tokens are processed in the same order that they appear in the document." }, { "code": null, "e": 24269, "s": 24196, "text": "Tokens are processed in the same order that they appear in the document." }, { "code": null, "e": 24369, "s": 24269, "text": "Reports the application program the nature of tokens that the parser has encountered as they occur." }, { "code": null, "e": 24469, "s": 24369, "text": "Reports the application program the nature of tokens that the parser has encountered as they occur." }, { "code": null, "e": 24562, "s": 24469, "text": "The application program provides an \"event\" handler that must be registered with the parser." }, { "code": null, "e": 24655, "s": 24562, "text": "The application program provides an \"event\" handler that must be registered with the parser." }, { "code": null, "e": 24760, "s": 24655, "text": "As the tokens are identified, callback methods in the handler are invoked with the relevant information." }, { "code": null, "e": 24865, "s": 24760, "text": "As the tokens are identified, callback methods in the handler are invoked with the relevant information." }, { "code": null, "e": 24900, "s": 24865, "text": "You should use a SAX parser when −" }, { "code": null, "e": 24971, "s": 24900, "text": "You can process the XML document in a linear fashion from top to down." }, { "code": null, "e": 25042, "s": 24971, "text": "You can process the XML document in a linear fashion from top to down." }, { "code": null, "e": 25077, "s": 25042, "text": "The document is not deeply nested." }, { "code": null, "e": 25112, "s": 25077, "text": "The document is not deeply nested." }, { "code": null, "e": 25285, "s": 25112, "text": "You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML." }, { "code": null, "e": 25458, "s": 25285, "text": "You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML." }, { "code": null, "e": 25525, "s": 25458, "text": "The problem to be solved involves only a part of the XML document." }, { "code": null, "e": 25592, "s": 25525, "text": "The problem to be solved involves only a part of the XML document." }, { "code": null, "e": 25713, "s": 25592, "text": "Data is available as soon as it is seen by the parser, so SAX works well for an XML document that arrives over a stream." }, { "code": null, "e": 25834, "s": 25713, "text": "Data is available as soon as it is seen by the parser, so SAX works well for an XML document that arrives over a stream." }, { "code": null, "e": 25926, "s": 25834, "text": "We have no random access to an XML document since it is processed in a forward-only manner." }, { "code": null, "e": 26018, "s": 25926, "text": "We have no random access to an XML document since it is processed in a forward-only manner." }, { "code": null, "e": 26163, "s": 26018, "text": "If you need to keep track of data that the parser has seen or change the order of items, you must write the code and store the data on your own." }, { "code": null, "e": 26308, "s": 26163, "text": "If you need to keep track of data that the parser has seen or change the order of items, you must write the code and store the data on your own." }, { "code": null, "e": 26468, "s": 26308, "text": "This interface specifies the callback methods that the SAX parser uses to notify an application program of the components of the XML document that it has seen." }, { "code": null, "e": 26530, "s": 26468, "text": "void startDocument() − Called at the beginning of a document." }, { "code": null, "e": 26592, "s": 26530, "text": "void startDocument() − Called at the beginning of a document." }, { "code": null, "e": 26646, "s": 26592, "text": "void endDocument() − Called at the end of a document." }, { "code": null, "e": 26700, "s": 26646, "text": "void endDocument() − Called at the end of a document." }, { "code": null, "e": 26820, "s": 26700, "text": "void startElement(String uri, String localName, String qName, Attributes atts) − Called at the beginning of an element." }, { "code": null, "e": 26940, "s": 26820, "text": "void startElement(String uri, String localName, String qName, Attributes atts) − Called at the beginning of an element." }, { "code": null, "e": 27034, "s": 26940, "text": "void endElement(String uri, String localName,String qName) − Called at the end of an element." }, { "code": null, "e": 27128, "s": 27034, "text": "void endElement(String uri, String localName,String qName) − Called at the end of an element." }, { "code": null, "e": 27223, "s": 27128, "text": "void characters(char[] ch, int start, int length) − Called when character data is encountered." }, { "code": null, "e": 27318, "s": 27223, "text": "void characters(char[] ch, int start, int length) − Called when character data is encountered." }, { "code": null, "e": 27450, "s": 27318, "text": "void ignorableWhitespace( char[] ch, int start, int length) − Called when a DTD is present and ignorable whitespace is encountered." }, { "code": null, "e": 27582, "s": 27450, "text": "void ignorableWhitespace( char[] ch, int start, int length) − Called when a DTD is present and ignorable whitespace is encountered." }, { "code": null, "e": 27691, "s": 27582, "text": "void processingInstruction(String target, String data) − Called when a processing instruction is recognized." }, { "code": null, "e": 27800, "s": 27691, "text": "void processingInstruction(String target, String data) − Called when a processing instruction is recognized." }, { "code": null, "e": 27919, "s": 27800, "text": "void setDocumentLocator(Locator locator)) − Provides a Locator that can be used to identify positions in the document." }, { "code": null, "e": 28038, "s": 27919, "text": "void setDocumentLocator(Locator locator)) − Provides a Locator that can be used to identify positions in the document." }, { "code": null, "e": 28121, "s": 28038, "text": "void skippedEntity(String name) − Called when an unresolved entity is encountered." }, { "code": null, "e": 28204, "s": 28121, "text": "void skippedEntity(String name) − Called when an unresolved entity is encountered." }, { "code": null, "e": 28305, "s": 28204, "text": "void startPrefixMapping(String prefix, String uri) − Called when a new namespace mapping is defined." }, { "code": null, "e": 28406, "s": 28305, "text": "void startPrefixMapping(String prefix, String uri) − Called when a new namespace mapping is defined." }, { "code": null, "e": 28496, "s": 28406, "text": "void endPrefixMapping(String prefix) − Called when a namespace definition ends its scope." }, { "code": null, "e": 28586, "s": 28496, "text": "void endPrefixMapping(String prefix) − Called when a namespace definition ends its scope." }, { "code": null, "e": 28674, "s": 28586, "text": "This interface specifies methods for processing the attributes connected to an element." }, { "code": null, "e": 28722, "s": 28674, "text": "int getLength() − Returns number of attributes." }, { "code": null, "e": 28770, "s": 28722, "text": "int getLength() − Returns number of attributes." }, { "code": null, "e": 28797, "s": 28770, "text": "String getQName(int index)" }, { "code": null, "e": 28824, "s": 28797, "text": "String getQName(int index)" }, { "code": null, "e": 28851, "s": 28824, "text": "String getValue(int index)" }, { "code": null, "e": 28878, "s": 28851, "text": "String getValue(int index)" }, { "code": null, "e": 28908, "s": 28878, "text": "String getValue(String qname)" }, { "code": null, "e": 28938, "s": 28908, "text": "String getValue(String qname)" }, { "code": null, "e": 28984, "s": 28938, "text": "Here is the input xml file we need to parse −" }, { "code": null, "e": 29535, "s": 28984, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 31356, "s": 29535, "text": "package com.tutorialspoint.xml;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n\n @Override\n public void startElement(String uri, \n String localName, String qName, Attributes attributes) throws SAXException {\n\n if (qName.equalsIgnoreCase(\"student\")) {\n String rollNo = attributes.getValue(\"rollno\");\n System.out.println(\"Roll No : \" + rollNo);\n } else if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(String uri, \n String localName, String qName) throws SAXException {\n if (qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n @Override\n public void characters(char ch[], int start, int length) throws SAXException {\n \n if (bFirstName) {\n System.out.println(\"First Name: \" \n + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 33724, "s": 31356, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXParserDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = SAXParserFactory.newInstance();\n SAXParser saxParser = factory.newSAXParser();\n UserHandler userhandler = new UserHandler();\n saxParser.parse(inputFile, userhandler); \n } catch (Exception e) {\n e.printStackTrace();\n }\n } \n}\n\nclass UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n\n @Override\n public void startElement(\n String uri, String localName, String qName, Attributes attributes)\n throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n String rollNo = attributes.getValue(\"rollno\");\n System.out.println(\"Roll No : \" + rollNo);\n } else if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(String uri, \n String localName, String qName) throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n @Override\n public void characters(char ch[], int start, int length) throws SAXException {\n\n if (bFirstName) {\n System.out.println(\"First Name: \" + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 33766, "s": 33724, "text": "This would produce the following result −" }, { "code": null, "e": 34059, "s": 33766, "text": "Roll No : 393\nFirst Name: dinkar\nLast Name: kad\nNick Name: dinkar\nMarks: 85\nEnd Element :student\nRoll No : 493\nFirst Name: Vaneet\nLast Name: Gupta\nNick Name: vinni\nMarks: 95\nEnd Element :student\nRoll No : 593\nFirst Name: jasvir\nLast Name: singn\nNick Name: jazz\nMarks: 90\nEnd Element :student\n" }, { "code": null, "e": 34125, "s": 34059, "text": "Here is the input text file that we need to Query for rollno: 393" }, { "code": null, "e": 34676, "s": 34125, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 36842, "s": 34676, "text": "package com.tutorialspoint.xml;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n \npublic class UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n String rollNo = null;\n\n @Override\n public void startElement(\n String uri, String localName, String qName, Attributes attributes)\n throws SAXException {\n\n if (qName.equalsIgnoreCase(\"student\")) {\n rollNo = attributes.getValue(\"rollno\");\n }\n if((\"393\").equals(rollNo) && \n qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"Start Element :\" + qName); \n } \n if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(\n String uri, String localName, String qName) throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n if((\"393\").equals(rollNo) && qName.equalsIgnoreCase(\"student\"))\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n @Override\n public void characters(char ch[], int start, int length) throws SAXException {\n\n if (bFirstName && (\"393\").equals(rollNo)) {\n //age element, set Employee age\n System.out.println(\"First Name: \" + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName && (\"393\").equals(rollNo)) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName && (\"393\").equals(rollNo)) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks && (\"393\").equals(rollNo)) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 39565, "s": 36842, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXQueryDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = SAXParserFactory.newInstance();\n SAXParser saxParser = factory.newSAXParser();\n UserHandler userhandler = new UserHandler();\n saxParser.parse(inputFile, userhandler); \n } catch (Exception e) {\n e.printStackTrace();\n }\n } \n}\n\nclass UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n String rollNo = null;\n\n @Override\n public void startElement(String uri, \n String localName, String qName, Attributes attributes)\n throws SAXException {\n\n if (qName.equalsIgnoreCase(\"student\")) {\n rollNo = attributes.getValue(\"rollno\");\n }\n if((\"393\").equals(rollNo) && qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"Start Element :\" + qName); \n } \n if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(\n String uri, String localName, String qName) throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n\n if((\"393\").equals(rollNo) \n && qName.equalsIgnoreCase(\"student\"))\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n\n @Override\n public void characters(\n char ch[], int start, int length) throws SAXException {\n\n if (bFirstName && (\"393\").equals(rollNo)) {\n //age element, set Employee age\n System.out.println(\"First Name: \" + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName && (\"393\").equals(rollNo)) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName && (\"393\").equals(rollNo)) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks && (\"393\").equals(rollNo)) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 39607, "s": 39565, "text": "This would produce the following result −" }, { "code": null, "e": 39714, "s": 39607, "text": "Start Element :student\nFirst Name: dinkar\nLast Name: kad\nNick Name: dinkar\nMarks: 85\nEnd Element :student\n" }, { "code": null, "e": 39859, "s": 39714, "text": "It is better to use StAX parser for creating XML documents rather than using SAX parser. Please refer the Java StAX Parser section for the same." }, { "code": null, "e": 39972, "s": 39859, "text": "Here is the input XML file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag." }, { "code": null, "e": 40523, "s": 39972, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 44217, "s": 40523, "text": "package com.tutorialspoint.xml;\n\nimport java.io.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXModifyDemo extends DefaultHandler {\n static String displayText[] = new String[1000];\n static int numberLines = 0;\n static String indentation = \"\";\n\n public static void main(String args[]) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = \n SAXParserFactory.newInstance();\n SAXModifyDemo obj = new SAXModifyDemo();\n obj.childLoop(inputFile);\n FileWriter filewriter = new FileWriter(\"newfile.xml\");\n \n for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {\n filewriter.write(displayText[loopIndex].toCharArray());\n filewriter.write('\\n');\n System.out.println(displayText[loopIndex].toString());\n }\n filewriter.close();\n }\n catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public void childLoop(File input) {\n DefaultHandler handler = this;\n SAXParserFactory factory = SAXParserFactory.newInstance();\n \n try {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(input, handler);\n } catch (Throwable t) {}\n }\n\n public void startDocument() {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"<?xml version = \\\"1.0\\\" encoding = \\\"\"+\n \"UTF-8\" + \"\\\"?>\";\n numberLines++;\n }\n\n public void processingInstruction(String target, String data) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"<?\";\n displayText[numberLines] += target;\n \n if (data != null && data.length() > 0) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += data;\n }\n displayText[numberLines] += \"?>\";\n numberLines++;\n }\n\n public void startElement(String uri, String localName, String qualifiedName,\n Attributes attributes) {\n\n displayText[numberLines] = indentation;\n\n indentation += \" \";\n\n displayText[numberLines] += '<';\n displayText[numberLines] += qualifiedName;\n \n if (attributes != null) {\n int numberAttributes = attributes.getLength();\n\n for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += attributes.getQName(loopIndex);\n displayText[numberLines] += \"=\\\"\";\n displayText[numberLines] += attributes.getValue(loopIndex);\n displayText[numberLines] += '\"';\n }\n }\n displayText[numberLines] += '>';\n numberLines++;\n }\n\n public void characters(char characters[], int start, int length) {\n String characterData = (new String(characters, start, length)).trim();\n \n if(characterData.indexOf(\"\\n\") < 0 && characterData.length() > 0) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += characterData;\n numberLines++;\n }\n }\n\n public void endElement(String uri, String localName, String qualifiedName) {\n indentation = indentation.substring(0, indentation.length() - 4) ;\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"</\";\n displayText[numberLines] += qualifiedName;\n displayText[numberLines] += '>';\n numberLines++;\n\n if (qualifiedName.equals(\"marks\")) {\n startElement(\"\", \"Result\", \"Result\", null);\n characters(\"Pass\".toCharArray(), 0, \"Pass\".length());\n endElement(\"\", \"Result\", \"Result\");\n }\n }\n}" }, { "code": null, "e": 44259, "s": 44217, "text": "This would produce the following result −" }, { "code": null, "e": 45161, "s": 44259, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<class>\n <student rollno = \"393\">\n <firstname>\n dinkar\n </firstname>\n <lastname>\n kad\n </lastname>\n <nickname>\n dinkar\n </nickname>\n <marks>\n 85\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n <student rollno = \"493\">\n <firstname>\n Vaneet\n </firstname>\n <lastname>\n Gupta\n </lastname>\n <nickname>\n vinni\n </nickname>\n <marks>\n 95\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n <student rollno = \"593\">\n <firstname>\n jasvir\n </firstname>\n <lastname>\n singn\n </lastname>\n <nickname>\n jazz\n </nickname>\n <marks>\n 90\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n</class>\n" }, { "code": null, "e": 45347, "s": 45161, "text": "JDOM is an open source, Java-based library to parse XML documents. It is typically a Java developer friendly API. It is Java optimized and it uses Java collections like List and Arrays." }, { "code": null, "e": 45474, "s": 45347, "text": "JDOM works with DOM and SAX APIs and combines the best of the two. It is of low memory footprint and is nearly as fast as SAX." }, { "code": null, "e": 45586, "s": 45474, "text": "In order to use JDOM parser, you should have jdom.jar in your application's classpath. Download jdom-2.0.5.zip." }, { "code": null, "e": 45622, "s": 45586, "text": "You should use a JDOM parser when −" }, { "code": null, "e": 45685, "s": 45622, "text": "You need to know a lot about the structure of an XML document." }, { "code": null, "e": 45748, "s": 45685, "text": "You need to know a lot about the structure of an XML document." }, { "code": null, "e": 45853, "s": 45748, "text": "You need to move parts of an XMl document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 45958, "s": 45853, "text": "You need to move parts of an XMl document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 46025, "s": 45958, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 46092, "s": 46025, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 46169, "s": 46092, "text": "You are a Java developer and want to leverage Java optimized parsing of XML." }, { "code": null, "e": 46246, "s": 46169, "text": "You are a Java developer and want to leverage Java optimized parsing of XML." }, { "code": null, "e": 46460, "s": 46246, "text": "When you parse an XML document with a JDOM parser, you get the flexibility to get back a tree structure that contains all of the elements of your document without impacting the memory footprint of the application." }, { "code": null, "e": 46647, "s": 46460, "text": "JDOM provides a variety of utility functions that you can use to examine the contents and structure of an XML document in case the document is well structured and its structure is known." }, { "code": null, "e": 46773, "s": 46647, "text": "JDOM provides Java developers the flexibility and easy maintainablity of XML parsing code. It is a lightweight and quick API." }, { "code": null, "e": 46843, "s": 46773, "text": "JDOM defines several Java classes. Here are the most common classes −" }, { "code": null, "e": 46943, "s": 46843, "text": "Document − Represents an entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 47043, "s": 46943, "text": "Document − Represents an entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 47179, "s": 47043, "text": "Element − Represents an XML element. Element object has methods to manipulate its child elements, its text, attributes, and namespaces." }, { "code": null, "e": 47315, "s": 47179, "text": "Element − Represents an XML element. Element object has methods to manipulate its child elements, its text, attributes, and namespaces." }, { "code": null, "e": 47460, "s": 47315, "text": "Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type." }, { "code": null, "e": 47605, "s": 47460, "text": "Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type." }, { "code": null, "e": 47644, "s": 47605, "text": "Text − Represents the text of XML tag." }, { "code": null, "e": 47683, "s": 47644, "text": "Text − Represents the text of XML tag." }, { "code": null, "e": 47736, "s": 47683, "text": "Comment − Represents the comments in a XML document." }, { "code": null, "e": 47789, "s": 47736, "text": "Comment − Represents the comments in a XML document." }, { "code": null, "e": 47866, "s": 47789, "text": "When you are working with JDOM, there are several methods you'll use often −" }, { "code": null, "e": 47943, "s": 47866, "text": "SAXBuilder.build(xmlSource)() − Build the JDOM document from the xml source." }, { "code": null, "e": 48020, "s": 47943, "text": "SAXBuilder.build(xmlSource)() − Build the JDOM document from the xml source." }, { "code": null, "e": 48081, "s": 48020, "text": "Document.getRootElement() − Get the root element of the XML." }, { "code": null, "e": 48142, "s": 48081, "text": "Document.getRootElement() − Get the root element of the XML." }, { "code": null, "e": 48192, "s": 48142, "text": "Element.getName() − Get the name of the XML node." }, { "code": null, "e": 48242, "s": 48192, "text": "Element.getName() − Get the name of the XML node." }, { "code": null, "e": 48312, "s": 48242, "text": "Element.getChildren() − Get all the direct child nodes of an element." }, { "code": null, "e": 48382, "s": 48312, "text": "Element.getChildren() − Get all the direct child nodes of an element." }, { "code": null, "e": 48457, "s": 48382, "text": "Node.getChildren(Name) − Get all the direct child nodes with a given name." }, { "code": null, "e": 48532, "s": 48457, "text": "Node.getChildren(Name) − Get all the direct child nodes with a given name." }, { "code": null, "e": 48600, "s": 48532, "text": "Node.getChild(Name) − Get the first child node with the given name." }, { "code": null, "e": 48668, "s": 48600, "text": "Node.getChild(Name) − Get the first child node with the given name." }, { "code": null, "e": 48741, "s": 48668, "text": "Following are the steps used while parsing a document using JDOM Parser." }, { "code": null, "e": 48770, "s": 48741, "text": "Import XML-related packages." }, { "code": null, "e": 48790, "s": 48770, "text": "Create a SAXBuilder" }, { "code": null, "e": 48830, "s": 48790, "text": "Create a Document from a file or stream" }, { "code": null, "e": 48855, "s": 48830, "text": "Extract the root element" }, { "code": null, "e": 48874, "s": 48855, "text": "Examine attributes" }, { "code": null, "e": 48895, "s": 48874, "text": "Examine sub-elements" }, { "code": null, "e": 48953, "s": 48895, "text": "import java.io.*;\nimport java.util.*;\nimport org.jdom2.*;" }, { "code": null, "e": 48995, "s": 48953, "text": "SAXBuilder saxBuilder = new SAXBuilder();" }, { "code": null, "e": 49126, "s": 48995, "text": "File inputFile = new File(\"input.txt\");\nSAXBuilder saxBuilder = new SAXBuilder();\nDocument document = saxBuilder.build(inputFile);" }, { "code": null, "e": 49176, "s": 49126, "text": "Element classElement = document.getRootElement();" }, { "code": null, "e": 49237, "s": 49176, "text": "//returns specific attribute\ngetAttribute(\"attributeName\"); " }, { "code": null, "e": 49429, "s": 49237, "text": "//returns a list of subelements of specified name\ngetChildren(\"subelementName\"); \n\n//returns a list of all child nodes\ngetChildren(); \n\n//returns first child node\ngetChild(\"subelementName\"); " }, { "code": null, "e": 49475, "s": 49429, "text": "Here is the input xml file we need to parse −" }, { "code": null, "e": 50026, "s": 49475, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 51706, "s": 50026, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.JDOMException;\nimport org.jdom2.input.SAXBuilder;\n\n\npublic class JDomParserDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXBuilder saxBuilder = new SAXBuilder();\n Document document = saxBuilder.build(inputFile);\n System.out.println(\"Root element :\" + document.getRootElement().getName());\n Element classElement = document.getRootElement();\n\n List<Element> studentList = classElement.getChildren();\n System.out.println(\"----------------------------\");\n\n for (int temp = 0; temp < studentList.size(); temp++) { \n Element student = studentList.get(temp);\n System.out.println(\"\\nCurrent Element :\" \n + student.getName());\n Attribute attribute = student.getAttribute(\"rollno\");\n System.out.println(\"Student roll no : \" \n + attribute.getValue() );\n System.out.println(\"First Name : \"\n + student.getChild(\"firstname\").getText());\n System.out.println(\"Last Name : \"\n + student.getChild(\"lastname\").getText());\n System.out.println(\"Nick Name : \"\n + student.getChild(\"nickname\").getText());\n System.out.println(\"Marks : \"\n + student.getChild(\"marks\").getText());\n }\n } catch(JDOMException e) {\n e.printStackTrace();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 51748, "s": 51706, "text": "This would produce the following result −" }, { "code": null, "e": 52141, "s": 51748, "text": "Root element :class\n----------------------------\n\nCurrent Element :student\nStudent roll no : 393\nFirst Name : dinkar\nLast Name : kad\nNick Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : 593\nFirst Name : jasvir\nLast Name : singn\nNick Name : jazz\nMarks : 90\n" }, { "code": null, "e": 52192, "s": 52141, "text": "Here is the input xml file that we need to query −" }, { "code": null, "e": 52798, "s": 52192, "text": "<?xml version = \"1.0\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferarri 101</carname>\n <carname type = \"sports car\">Ferarri 201</carname>\n <carname type = \"sports car\">Ferarri 301</carname>\n </supercars>\n \n <supercars company = \"Lamborgini\">\n <carname>Lamborgini 001</carname>\n <carname>Lamborgini 002</carname>\n <carname>Lamborgini 003</carname>\n </supercars>\n \n <luxurycars company = \"Benteley\">\n <carname>Benteley 1</carname>\n <carname>Benteley 2</carname>\n <carname>Benteley 3</carname>\n </luxurycars>\n</cars>" }, { "code": null, "e": 54736, "s": 52798, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.JDOMException;\nimport org.jdom2.input.SAXBuilder;\n\n\npublic class QueryXmlFileDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXBuilder saxBuilder = new SAXBuilder();\n Document document = saxBuilder.build(inputFile);\n System.out.println(\"Root element :\" + document.getRootElement().getName());\n Element classElement = document.getRootElement();\n\n List<Element> supercarList = classElement.getChildren(\"supercars\");\n System.out.println(\"----------------------------\");\n\n for (int temp = 0; temp < supercarList.size(); temp++) { \n Element supercarElement = supercarList.get(temp);\n System.out.println(\"\\nCurrent Element :\" + supercarElement.getName());\n Attribute attribute = supercarElement.getAttribute(\"company\");\n System.out.println(\"company : \" + attribute.getValue() );\n List<Element> carNameList = supercarElement.getChildren(\"carname\");\n \n for (int count = 0; count < carNameList.size(); count++) {\t \n Element carElement = carNameList.get(count);\n System.out.print(\"car name : \");\n System.out.println(carElement.getText());\n System.out.print(\"car type : \");\n Attribute typeAttribute = carElement.getAttribute(\"type\");\n \n if(typeAttribute != null)\n System.out.println(typeAttribute.getValue());\n else {\n System.out.println(\"\");\n }\n }\n }\n } catch(JDOMException e) {\n e.printStackTrace();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 54778, "s": 54736, "text": "This would produce the following result −" }, { "code": null, "e": 55172, "s": 54778, "text": "Root element :cars\n----------------------------\n\nCurrent Element :supercars\ncompany : Ferrari\ncar name : Ferarri 101\ncar type : formula one\ncar name : Ferarri 201\ncar type : sports car\ncar name : Ferarri 301\ncar type : sports car\n\nCurrent Element :supercars\ncompany : Lamborgini\ncar name : Lamborgini 001\ncar type : \ncar name : Lamborgini 002\ncar type : \ncar name : Lamborgini 003\ncar type : \n" }, { "code": null, "e": 55218, "s": 55172, "text": "Here is the XML file that we need to create −" }, { "code": null, "e": 55438, "s": 55218, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 56790, "s": 55438, "text": "import java.io.IOException;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.output.Format;\nimport org.jdom2.output.XMLOutputter;\n\n\npublic class CreateXmlFileDemo {\n\n public static void main(String[] args) {\n\n try{\n //root element\n Element carsElement = new Element(\"cars\");\n Document doc = new Document(carsElement);\n\n //supercars element\n Element supercarElement = new Element(\"supercars\");\n supercarElement.setAttribute(new Attribute(\"company\",\"Ferrari\"));\n\n //supercars element\n Element carElement1 = new Element(\"carname\");\n carElement1.setAttribute(new Attribute(\"type\",\"formula one\"));\n carElement1.setText(\"Ferrari 101\");\n\n Element carElement2 = new Element(\"carname\");\n carElement2.setAttribute(new Attribute(\"type\",\"sports\"));\n carElement2.setText(\"Ferrari 202\");\n\n supercarElement.addContent(carElement1);\n supercarElement.addContent(carElement2);\n\n doc.getRootElement().addContent(supercarElement);\n\n XMLOutputter xmlOutput = new XMLOutputter();\n\n // display ml\n xmlOutput.setFormat(Format.getPrettyFormat());\n xmlOutput.output(doc, System.out); \n } catch(IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 56832, "s": 56790, "text": "This would produce the following result −" }, { "code": null, "e": 57053, "s": 56832, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 57106, "s": 57053, "text": "Here is the input text file that we need to modify −" }, { "code": null, "e": 57510, "s": 57106, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n \n <luxurycars company = \"Benteley\">\n <carname>Benteley 1</carname>\n <carname>Benteley 2</carname>\n <carname>Benteley 3</carname>\n </luxurycars>\n</cars>" }, { "code": null, "e": 59602, "s": 57510, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.JDOMException;\nimport org.jdom2.input.SAXBuilder;\nimport org.jdom2.output.Format;\nimport org.jdom2.output.XMLOutputter;\n\n\npublic class ModifyXMLFileDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXBuilder saxBuilder = new SAXBuilder();\n Document document = saxBuilder.build(inputFile);\n Element rootElement = document.getRootElement();\n\n //get first supercar\n Element supercarElement = rootElement.getChild(\"supercars\");\n\n // update supercar attribute\n Attribute attribute = supercarElement.getAttribute(\"company\");\n attribute.setValue(\"Lamborigini\");\n\n // loop the supercar child node\n List<Element> list = supercarElement.getChildren();\n \n for (int temp = 0; temp < list.size(); temp++) {\n Element carElement = list.get(temp);\n \n if(\"Ferrari 101\".equals(carElement.getText())) {\n carElement.setText(\"Lamborigini 001\");\n }\n if(\"Ferrari 202\".equals(carElement.getText())) {\n carElement.setText(\"Lamborigini 002\");\n }\n }\n\n //get all supercars element\n List<Element> supercarslist = rootElement.getChildren();\n \n for (int temp = 0; temp < supercarslist.size(); temp++) {\n Element tempElement = supercarslist.get(temp);\n \n if(\"luxurycars\".equals(tempElement.getName())) {\n rootElement.removeContent(tempElement);\n } \t \n }\n\n XMLOutputter xmlOutput = new XMLOutputter();\n \n // display xml\n xmlOutput.setFormat(Format.getPrettyFormat());\n xmlOutput.output(document, System.out); \n } catch (JDOMException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 59644, "s": 59602, "text": "This would produce the following result −" }, { "code": null, "e": 59877, "s": 59644, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Lamborigini\">\n <carname type = \"formula one\">Lamborigini 001</carname>\n <carname type = \"sports\">Lamborigini 002</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 60019, "s": 59877, "text": "StAX is a Java-based API to parse XML document in a similar way as SAX parser does. But there are two major difference between the two APIs −" }, { "code": null, "e": 60354, "s": 60019, "text": "StAX is a PULL API, whereas SAX is a PUSH API. It means in case of StAX parser, a client application needs to ask the StAX parser to get information from XML whenever it needs. But in case of SAX parser, a client application is required to get information when SAX parser notifies the client application that information is available." }, { "code": null, "e": 60689, "s": 60354, "text": "StAX is a PULL API, whereas SAX is a PUSH API. It means in case of StAX parser, a client application needs to ask the StAX parser to get information from XML whenever it needs. But in case of SAX parser, a client application is required to get information when SAX parser notifies the client application that information is available." }, { "code": null, "e": 60784, "s": 60689, "text": "StAX API can read as well as write XML documents. Using SAX API, an XML file can only be read." }, { "code": null, "e": 60879, "s": 60784, "text": "StAX API can read as well as write XML documents. Using SAX API, an XML file can only be read." }, { "code": null, "e": 60966, "s": 60879, "text": "In order to use StAX parser, you should have stax.jar in your application's classpath." }, { "code": null, "e": 61007, "s": 60966, "text": "Following are the features of StAX API −" }, { "code": null, "e": 61113, "s": 61007, "text": "Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document." }, { "code": null, "e": 61219, "s": 61113, "text": "Reads an XML document from top to bottom, recognizing the tokens that make up a well-formed XML document." }, { "code": null, "e": 61292, "s": 61219, "text": "Tokens are processed in the same order that they appear in the document." }, { "code": null, "e": 61365, "s": 61292, "text": "Tokens are processed in the same order that they appear in the document." }, { "code": null, "e": 61465, "s": 61365, "text": "Reports the application program the nature of tokens that the parser has encountered as they occur." }, { "code": null, "e": 61565, "s": 61465, "text": "Reports the application program the nature of tokens that the parser has encountered as they occur." }, { "code": null, "e": 61778, "s": 61565, "text": "The application program provides an \"event\" reader which acts as an iterator and iterates over the event to get the required information. Another reader available is \"cursor\" which acts as a pointer to XML nodes." }, { "code": null, "e": 61991, "s": 61778, "text": "The application program provides an \"event\" reader which acts as an iterator and iterates over the event to get the required information. Another reader available is \"cursor\" which acts as a pointer to XML nodes." }, { "code": null, "e": 62103, "s": 61991, "text": "As the events are identified, XML elements can be retrieved from the event object and can be processed further." }, { "code": null, "e": 62215, "s": 62103, "text": "As the events are identified, XML elements can be retrieved from the event object and can be processed further." }, { "code": null, "e": 62251, "s": 62215, "text": "You should use a StAX parser when −" }, { "code": null, "e": 62322, "s": 62251, "text": "You can process the XML document in a linear fashion from top to down." }, { "code": null, "e": 62393, "s": 62322, "text": "You can process the XML document in a linear fashion from top to down." }, { "code": null, "e": 62428, "s": 62393, "text": "The document is not deeply nested." }, { "code": null, "e": 62463, "s": 62428, "text": "The document is not deeply nested." }, { "code": null, "e": 62636, "s": 62463, "text": "You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML." }, { "code": null, "e": 62809, "s": 62636, "text": "You are processing a very large XML document whose DOM tree would consume too much memory. Typical DOM implementations use ten bytes of memory to represent one byte of XML." }, { "code": null, "e": 62876, "s": 62809, "text": "The problem to be solved involves only a part of the XML document." }, { "code": null, "e": 62943, "s": 62876, "text": "The problem to be solved involves only a part of the XML document." }, { "code": null, "e": 63065, "s": 62943, "text": "Data is available as soon as it is seen by the parser, so StAX works well for an XML document that arrives over a stream." }, { "code": null, "e": 63187, "s": 63065, "text": "Data is available as soon as it is seen by the parser, so StAX works well for an XML document that arrives over a stream." }, { "code": null, "e": 63280, "s": 63187, "text": "We have no random access to an XML document, since it is processed in a forward-only manner." }, { "code": null, "e": 63373, "s": 63280, "text": "We have no random access to an XML document, since it is processed in a forward-only manner." }, { "code": null, "e": 63545, "s": 63373, "text": "If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own." }, { "code": null, "e": 63717, "s": 63545, "text": "If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own." }, { "code": null, "e": 63842, "s": 63717, "text": "This class provides iterator of events which can be used to iterate over events as they occur while parsing an XML document." }, { "code": null, "e": 63931, "s": 63842, "text": "StartElement asStartElement() − Used to retrieve the value and attributes of an element." }, { "code": null, "e": 64020, "s": 63931, "text": "StartElement asStartElement() − Used to retrieve the value and attributes of an element." }, { "code": null, "e": 64081, "s": 64020, "text": "EndElement asEndElement() − Called at the end of an element." }, { "code": null, "e": 64142, "s": 64081, "text": "EndElement asEndElement() − Called at the end of an element." }, { "code": null, "e": 64235, "s": 64142, "text": "Characters asCharacters() − Can be used to obtain characters such as CDATA, whitespace, etc." }, { "code": null, "e": 64328, "s": 64235, "text": "Characters asCharacters() − Can be used to obtain characters such as CDATA, whitespace, etc." }, { "code": null, "e": 64384, "s": 64328, "text": "This interface specifies methods for creating an event." }, { "code": null, "e": 64441, "s": 64384, "text": "add(Event event) − Add event containing elements to XML." }, { "code": null, "e": 64498, "s": 64441, "text": "add(Event event) − Add event containing elements to XML." }, { "code": null, "e": 64623, "s": 64498, "text": "This class provides iterator of events which can be used to iterate over events as they occur while parsing an XML document." }, { "code": null, "e": 64665, "s": 64623, "text": "int next() − Used to retrieve next event." }, { "code": null, "e": 64707, "s": 64665, "text": "int next() − Used to retrieve next event." }, { "code": null, "e": 64771, "s": 64707, "text": "boolean hasNext() − Used to check further events exists or not." }, { "code": null, "e": 64835, "s": 64771, "text": "boolean hasNext() − Used to check further events exists or not." }, { "code": null, "e": 64886, "s": 64835, "text": "String getText() − Used to get text of an element." }, { "code": null, "e": 64937, "s": 64886, "text": "String getText() − Used to get text of an element." }, { "code": null, "e": 64993, "s": 64937, "text": "String getLocalName() − Used to get name of an element." }, { "code": null, "e": 65049, "s": 64993, "text": "String getLocalName() − Used to get name of an element." }, { "code": null, "e": 65105, "s": 65049, "text": "This interface specifies methods for creating an event." }, { "code": null, "e": 65178, "s": 65105, "text": "writeStartElement(String localName) − Add a start element of given name." }, { "code": null, "e": 65251, "s": 65178, "text": "writeStartElement(String localName) − Add a start element of given name." }, { "code": null, "e": 65321, "s": 65251, "text": "writeEndElement(String localName) − Add an end element of given name." }, { "code": null, "e": 65391, "s": 65321, "text": "writeEndElement(String localName) − Add an end element of given name." }, { "code": null, "e": 65472, "s": 65391, "text": "writeAttribute(String localName, String value) − Write attributes to an element." }, { "code": null, "e": 65553, "s": 65472, "text": "writeAttribute(String localName, String value) − Write attributes to an element." }, { "code": null, "e": 65604, "s": 65553, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 66155, "s": 65604, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 69524, "s": 66155, "text": "package com.tutorialspoint.xml;\n\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.util.Iterator;\n\nimport javax.xml.stream.XMLEventReader;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamConstants;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.events.Attribute;\nimport javax.xml.stream.events.Characters;\nimport javax.xml.stream.events.EndElement;\nimport javax.xml.stream.events.StartElement;\nimport javax.xml.stream.events.XMLEvent;\n\npublic class StAXParserDemo {\n public static void main(String[] args) {\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n \n try {\n XMLInputFactory factory = XMLInputFactory.newInstance();\n XMLEventReader eventReader =\n factory.createXMLEventReader(new FileReader(\"input.txt\"));\n\n while(eventReader.hasNext()) {\n XMLEvent event = eventReader.nextEvent();\n \n switch(event.getEventType()) {\n \n case XMLStreamConstants.START_ELEMENT:\n StartElement startElement = event.asStartElement();\n String qName = startElement.getName().getLocalPart();\n\n if (qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"Start Element : student\");\n Iterator<Attribute> attributes = startElement.getAttributes();\n String rollNo = attributes.next().getValue();\n System.out.println(\"Roll No : \" + rollNo);\n } else if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n break;\n\n case XMLStreamConstants.CHARACTERS:\n Characters characters = event.asCharacters();\n if(bFirstName) {\n System.out.println(\"First Name: \" + characters.getData());\n bFirstName = false;\n }\n if(bLastName) {\n System.out.println(\"Last Name: \" + characters.getData());\n bLastName = false;\n }\n if(bNickName) {\n System.out.println(\"Nick Name: \" + characters.getData());\n bNickName = false;\n }\n if(bMarks) {\n System.out.println(\"Marks: \" + characters.getData());\n bMarks = false;\n }\n break;\n\n case XMLStreamConstants.END_ELEMENT:\n EndElement endElement = event.asEndElement();\n \n if(endElement.getName().getLocalPart().equalsIgnoreCase(\"student\")) {\n System.out.println(\"End Element : student\");\n System.out.println();\n }\n break;\n } \n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (XMLStreamException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 69566, "s": 69524, "text": "This would produce the following result −" }, { "code": null, "e": 69936, "s": 69566, "text": "Start Element : student\nRoll No : 393\nFirst Name: dinkar\nLast Name: kad\nNick Name: dinkar\nMarks: 85\nEnd Element : student\n\nStart Element : student\nRoll No : 493\nFirst Name: Vaneet\nLast Name: Gupta\nNick Name: vinni\nMarks: 95\nEnd Element : student\n\nStart Element : student\nRoll No : 593\nFirst Name: jasvir\nLast Name: singn\nNick Name: jazz\nMarks: 90\nEnd Element : student\n" }, { "code": null, "e": 69987, "s": 69936, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 70538, "s": 69987, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 74355, "s": 70538, "text": "package com.tutorialspoint.xml;\n\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.util.Iterator;\n\nimport javax.xml.stream.XMLEventReader;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamConstants;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.events.Attribute;\nimport javax.xml.stream.events.Characters;\nimport javax.xml.stream.events.EndElement;\nimport javax.xml.stream.events.StartElement;\nimport javax.xml.stream.events.XMLEvent;\n\npublic class StAXQueryDemo {\n public static void main(String[] args) {\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n boolean isRequestRollNo = false;\n \n try {\n XMLInputFactory factory = XMLInputFactory.newInstance();\n XMLEventReader eventReader =\n factory.createXMLEventReader(new FileReader(\"input.txt\"));\n\n String requestedRollNo = \"393\";\n \n while(eventReader.hasNext()) {\n XMLEvent event = eventReader.nextEvent();\n \n switch(event.getEventType()) {\n case XMLStreamConstants.START_ELEMENT:\n StartElement startElement = event.asStartElement();\n String qName = startElement.getName().getLocalPart();\n \n if (qName.equalsIgnoreCase(\"student\")) {\n Iterator<Attribute> attributes = startElement.getAttributes();\n String rollNo = attributes.next().getValue();\n \n if(rollNo.equalsIgnoreCase(requestedRollNo)) {\n System.out.println(\"Start Element : student\");\n System.out.println(\"Roll No : \" + rollNo);\n isRequestRollNo = true;\n }\n } else if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n break;\n \n case XMLStreamConstants.CHARACTERS:\n Characters characters = event.asCharacters();\n \n if(bFirstName && isRequestRollNo) {\n System.out.println(\"First Name: \" + characters.getData());\n bFirstName = false;\n }\n if(bLastName && isRequestRollNo) {\n System.out.println(\"Last Name: \" + characters.getData());\n bLastName = false;\n }\n if(bNickName && isRequestRollNo) {\n System.out.println(\"Nick Name: \" + characters.getData());\n bNickName = false;\n }\n if(bMarks && isRequestRollNo) {\n System.out.println(\"Marks: \" + characters.getData());\n bMarks = false;\n }\n break;\n \n case XMLStreamConstants.END_ELEMENT:\n EndElement endElement = event.asEndElement();\n \n if(endElement.getName().getLocalPart().equalsIgnoreCase(\n \"student\") && isRequestRollNo) {\n System.out.println(\"End Element : student\");\n System.out.println();\n isRequestRollNo = false;\n }\n break;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (XMLStreamException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 74397, "s": 74355, "text": "This would produce the following result −" }, { "code": null, "e": 74520, "s": 74397, "text": "Start Element : student\nRoll No : 393\nFirst Name: dinkar\nLast Name: kad\nNick Name: dinkar\nMarks: 85\nEnd Element : student\n" }, { "code": null, "e": 74561, "s": 74520, "text": "Here is the XML that we need to create −" }, { "code": null, "e": 74799, "s": 74561, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 76516, "s": 74799, "text": "package com.tutorialspoint.xml;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\n\nimport javax.xml.stream.XMLOutputFactory;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.XMLStreamWriter;\n\npublic class StAXCreateXMLDemo {\n\n public static void main(String[] args) {\n\n try {\n StringWriter stringWriter = new StringWriter();\n\n XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();\n XMLStreamWriter xMLStreamWriter =\n xMLOutputFactory.createXMLStreamWriter(stringWriter);\n \n xMLStreamWriter.writeStartDocument();\n xMLStreamWriter.writeStartElement(\"cars\");\n \n xMLStreamWriter.writeStartElement(\"supercars\");\t\n xMLStreamWriter.writeAttribute(\"company\", \"Ferrari\");\n \n xMLStreamWriter.writeStartElement(\"carname\");\n xMLStreamWriter.writeAttribute(\"type\", \"formula one\");\n xMLStreamWriter.writeCharacters(\"Ferrari 101\");\n xMLStreamWriter.writeEndElement();\n\n xMLStreamWriter.writeStartElement(\"carname\");\t\t\t\n xMLStreamWriter.writeAttribute(\"type\", \"sports\");\n xMLStreamWriter.writeCharacters(\"Ferrari 202\");\n xMLStreamWriter.writeEndElement();\n\n xMLStreamWriter.writeEndElement();\n xMLStreamWriter.writeEndDocument();\n\n xMLStreamWriter.flush();\n xMLStreamWriter.close();\n\n String xmlString = stringWriter.getBuffer().toString();\n\n stringWriter.close();\n\n System.out.println(xmlString);\n\n } catch (XMLStreamException e) {\n e.printStackTrace();\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 76558, "s": 76516, "text": "This would produce the following result −" }, { "code": null, "e": 76797, "s": 76558, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 76838, "s": 76797, "text": "Here is the XML that we need to modify −" }, { "code": null, "e": 77389, "s": 76838, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singh</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 80297, "s": 77389, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.xml.stream.XMLEventReader;\nimport javax.xml.stream.XMLInputFactory;\nimport javax.xml.stream.XMLStreamConstants;\nimport javax.xml.stream.XMLStreamException;\nimport javax.xml.stream.events.Attribute;\nimport javax.xml.stream.events.StartElement;\nimport javax.xml.stream.events.XMLEvent;\n\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.JDOMException;\nimport org.jdom2.input.SAXBuilder;\nimport org.jdom2.output.Format;\nimport org.jdom2.output.XMLOutputter;\n\npublic class StAXModifyDemo {\n\n public static void main(String[] args) {\n\n try {\n XMLInputFactory factory = XMLInputFactory.newInstance();\n XMLEventReader eventReader = factory.createXMLEventReader(\n new FileReader(\"input.txt\"));\n SAXBuilder saxBuilder = new SAXBuilder();\n Document document = saxBuilder.build(new File(\"input.txt\"));\n Element rootElement = document.getRootElement();\n List<Element> studentElements = rootElement.getChildren(\"student\");\n\n while(eventReader.hasNext()) {\n XMLEvent event = eventReader.nextEvent();\n \n switch(event.getEventType()) {\n case XMLStreamConstants.START_ELEMENT:\n StartElement startElement = event.asStartElement();\n String qName = startElement.getName().getLocalPart();\n\n if (qName.equalsIgnoreCase(\"student\")) {\n Iterator<Attribute> attributes = startElement.getAttributes();\n String rollNo = attributes.next().getValue();\n \n if(rollNo.equalsIgnoreCase(\"393\")) {\n //get the student with roll no 393\n\n for(int i = 0;i < studentElements.size();i++) {\n Element studentElement = studentElements.get(i);\n\n if(studentElement.getAttribute(\n \"rollno\").getValue().equalsIgnoreCase(\"393\")) {\n studentElement.removeChild(\"marks\");\n studentElement.addContent(new Element(\"marks\").setText(\"80\"));\n }\n }\n }\n }\n break;\n }\n }\n XMLOutputter xmlOutput = new XMLOutputter();\n\n // display xml\n xmlOutput.setFormat(Format.getPrettyFormat());\n xmlOutput.output(document, System.out);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (XMLStreamException e) {\n e.printStackTrace();\n } catch (JDOMException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 80339, "s": 80297, "text": "This would produce the following result −" }, { "code": null, "e": 80831, "s": 80339, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>80</marks>\n</student>\n<student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n</student>\n<student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singh</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n</student>\n" }, { "code": null, "e": 81149, "s": 80831, "text": "XPath is an official recommendation of the World Wide Web Consortium (W3C). It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document." }, { "code": null, "e": 81311, "s": 81149, "text": "Structure Definations − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes." }, { "code": null, "e": 81473, "s": 81311, "text": "Structure Definations − XPath defines the parts of an XML document like element, attribute, text, namespace, processing-instruction, comment, and document nodes." }, { "code": null, "e": 81589, "s": 81473, "text": "Path Expressions − XPath provides powerful path expressions such as select nodes or list of nodes in XML documents." }, { "code": null, "e": 81705, "s": 81589, "text": "Path Expressions − XPath provides powerful path expressions such as select nodes or list of nodes in XML documents." }, { "code": null, "e": 81928, "s": 81705, "text": "Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, etc." }, { "code": null, "e": 82151, "s": 81928, "text": "Standard Functions − XPath provides a rich library of standard functions for manipulation of string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, etc." }, { "code": null, "e": 82310, "s": 82151, "text": "Major part of XSLT − XPath is one of the major elements in XSLT standard and one must have sufficient knowledge of XPath in order to work with XSLT documents." }, { "code": null, "e": 82469, "s": 82310, "text": "Major part of XSLT − XPath is one of the major elements in XSLT standard and one must have sufficient knowledge of XPath in order to work with XSLT documents." }, { "code": null, "e": 82559, "s": 82469, "text": "W3C recommendation − XPath is official recommendation of World Wide Web Consortium (W3C)." }, { "code": null, "e": 82649, "s": 82559, "text": "W3C recommendation − XPath is official recommendation of World Wide Web Consortium (W3C)." }, { "code": null, "e": 82838, "s": 82649, "text": "XPath uses a path expression to select node or list of nodes from an XML document. Following is a list of useful paths and expression to select any node/list of nodes from an XML document." }, { "code": null, "e": 82848, "s": 82838, "text": "node-name" }, { "code": null, "e": 82896, "s": 82848, "text": "Select all nodes with the given name \"nodename\"" }, { "code": null, "e": 82898, "s": 82896, "text": "/" }, { "code": null, "e": 82934, "s": 82898, "text": "Selection starts from the root node" }, { "code": null, "e": 82937, "s": 82934, "text": "//" }, { "code": null, "e": 83001, "s": 82937, "text": "Selection starts from the current node that match the selection" }, { "code": null, "e": 83003, "s": 83001, "text": "." }, { "code": null, "e": 83028, "s": 83003, "text": "Selects the current node" }, { "code": null, "e": 83031, "s": 83028, "text": ".." }, { "code": null, "e": 83070, "s": 83031, "text": "Selects the parent of the current node" }, { "code": null, "e": 83072, "s": 83070, "text": "@" }, { "code": null, "e": 83091, "s": 83072, "text": "Selects attributes" }, { "code": null, "e": 83099, "s": 83091, "text": "student" }, { "code": null, "e": 83151, "s": 83099, "text": "Example − Selects all nodes with the name \"student\"" }, { "code": null, "e": 83165, "s": 83151, "text": "class/student" }, { "code": null, "e": 83231, "s": 83165, "text": "Example − Selects all student elements that are children of class" }, { "code": null, "e": 83241, "s": 83231, "text": "//student" }, { "code": null, "e": 83311, "s": 83241, "text": "Selects all student elements no matter where they are in the document" }, { "code": null, "e": 83418, "s": 83311, "text": "Predicates are used to find specific node or a node containing specific value and are defined using [...]." }, { "code": null, "e": 83492, "s": 83418, "text": "Following are the steps used while parsing a document using XPath Parser." }, { "code": null, "e": 83521, "s": 83492, "text": "Import XML-related packages." }, { "code": null, "e": 83550, "s": 83521, "text": "Import XML-related packages." }, { "code": null, "e": 83576, "s": 83550, "text": "Create a DocumentBuilder." }, { "code": null, "e": 83602, "s": 83576, "text": "Create a DocumentBuilder." }, { "code": null, "e": 83643, "s": 83602, "text": "Create a Document from a file or stream." }, { "code": null, "e": 83684, "s": 83643, "text": "Create a Document from a file or stream." }, { "code": null, "e": 83737, "s": 83684, "text": "Create an Xpath object and an XPath path expression." }, { "code": null, "e": 83790, "s": 83737, "text": "Create an Xpath object and an XPath path expression." }, { "code": null, "e": 83925, "s": 83790, "text": "Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate()." }, { "code": null, "e": 84060, "s": 83925, "text": "Compile the XPath expression using XPath.compile() and get a list of nodes by evaluating the compiled expression via XPath.evaluate()." }, { "code": null, "e": 84092, "s": 84060, "text": "Iterate over the list of nodes." }, { "code": null, "e": 84124, "s": 84092, "text": "Iterate over the list of nodes." }, { "code": null, "e": 84144, "s": 84124, "text": "Examine attributes." }, { "code": null, "e": 84164, "s": 84144, "text": "Examine attributes." }, { "code": null, "e": 84186, "s": 84164, "text": "Examine sub-elements." }, { "code": null, "e": 84208, "s": 84186, "text": "Examine sub-elements." }, { "code": null, "e": 84324, "s": 84208, "text": "import org.w3c.dom.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport javax.xml.xpath.*;\nimport java.io.*;" }, { "code": null, "e": 84451, "s": 84324, "text": "DocumentBuilderFactory factory =\nDocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();" }, { "code": null, "e": 84718, "s": 84451, "text": "StringBuilder xmlStringBuilder = new StringBuilder();\nxmlStringBuilder.append(\"<?xml version = \"1.0\"?> <class> </class>\");\nByteArrayInputStream input = new ByteArrayInputStream(\n xmlStringBuilder.toString().getBytes(\"UTF-8\"));\nDocument doc = builder.parse(input);" }, { "code": null, "e": 84772, "s": 84718, "text": "XPath xPath = XPathFactory.newInstance().newXPath();" }, { "code": null, "e": 84919, "s": 84772, "text": "String expression = \"/class/student\";\t \nNodeList nodeList = (NodeList) xPath.compile(expression).evaluate(\n doc, XPathConstants.NODESET);" }, { "code": null, "e": 85011, "s": 84919, "text": "for (int i = 0; i < nodeList.getLength(); i++) {\n Node nNode = nodeList.item(i);\n ...\n}" }, { "code": null, "e": 85130, "s": 85011, "text": "//returns specific attribute\ngetAttribute(\"attributeName\");\n\n//returns a Map (table) of names/values\ngetAttributes(); " }, { "code": null, "e": 85275, "s": 85130, "text": "//returns a list of subelements of specified name\ngetElementsByTagName(\"subelementName\");\n\n//returns a list of all child nodes\ngetChildNodes(); " }, { "code": null, "e": 85322, "s": 85275, "text": "Here is the input text file we need to parse −" }, { "code": null, "e": 85873, "s": 85322, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singh</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 88549, "s": 85873, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathExpressionException;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Element;\nimport org.xml.sax.SAXException;\n\npublic class XPathParserDemo {\n \n public static void main(String[] args) {\n \n try {\n File inputFile = new File(\"input.txt\");\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder;\n\n dBuilder = dbFactory.newDocumentBuilder();\n\n Document doc = dBuilder.parse(inputFile);\n doc.getDocumentElement().normalize();\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n\n String expression = \"/class/student\";\t \n NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(\n doc, XPathConstants.NODESET);\n\n for (int i = 0; i < nodeList.getLength(); i++) {\n Node nNode = nodeList.item(i);\n System.out.println(\"\\nCurrent Element :\" + nNode.getNodeName());\n \n if (nNode.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) nNode;\n System.out.println(\"Student roll no :\" + eElement.getAttribute(\"rollno\"));\n System.out.println(\"First Name : \" \n + eElement\n .getElementsByTagName(\"firstname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Last Name : \" \n + eElement\n .getElementsByTagName(\"lastname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Nick Name : \" \n + eElement\n .getElementsByTagName(\"nickname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Marks : \" \n + eElement\n .getElementsByTagName(\"marks\")\n .item(0)\n .getTextContent());\n }\n }\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (SAXException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (XPathExpressionException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 88591, "s": 88549, "text": "This would produce the following result −" }, { "code": null, "e": 88934, "s": 88591, "text": "Current Element :student\nStudent roll no : 393\nFirst Name : dinkar\nLast Name : kad\nNick Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : 593\nFirst Name : jasvir\nLast Name : singh\nNick Name : jazz\nMarks : 90\n" }, { "code": null, "e": 88986, "s": 88934, "text": "Here is the input text file that we need to query −" }, { "code": null, "e": 89537, "s": 88986, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 92247, "s": 89537, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathExpressionException;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.Element;\nimport org.xml.sax.SAXException;\n\npublic class XPathParserDemo {\n\n public static void main(String[] args) {\n \n try {\n File inputFile = new File(\"input.txt\");\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder;\n\n dBuilder = dbFactory.newDocumentBuilder();\n\n Document doc = dBuilder.parse(inputFile);\n doc.getDocumentElement().normalize();\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n\n String expression = \"/class/student[@rollno = '493']\";\n NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(\n doc, XPathConstants.NODESET);\n \n for (int i = 0; i < nodeList.getLength(); i++) {\n Node nNode = nodeList.item(i);\n System.out.println(\"\\nCurrent Element :\" + nNode.getNodeName());\n \n if (nNode.getNodeType() == Node.ELEMENT_NODE) {\n Element eElement = (Element) nNode;\n System.out.println(\"Student roll no : \" \n + eElement.getAttribute(\"rollno\"));\n System.out.println(\"First Name : \" \n + eElement\n .getElementsByTagName(\"firstname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Last Name : \" \n + eElement\n .getElementsByTagName(\"lastname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Nick Name : \" \n + eElement\n .getElementsByTagName(\"nickname\")\n .item(0)\n .getTextContent());\n System.out.println(\"Marks : \" \n + eElement\n .getElementsByTagName(\"marks\")\n .item(0)\n .getTextContent());\n }\n }\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (SAXException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (XPathExpressionException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 92289, "s": 92247, "text": "This would produce the following result −" }, { "code": null, "e": 92404, "s": 92289, "text": "Current Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n" }, { "code": null, "e": 92561, "s": 92404, "text": "XPath parser is used to navigate XML Documents only. It is better to use DOM parser for creating XML. Please refer the Java DOM Parser section for the same." }, { "code": null, "e": 92719, "s": 92561, "text": "XPath parser is used to navigate XML Documents only. It is better to use DOM parser for modifying XML. Please refer the Java DOM Parser section for the same." }, { "code": null, "e": 92906, "s": 92719, "text": "DOM4J is an open source, Java-based library to parse XML documents. It is a highly flexible and memory-efficient API. It is Java-optimized and uses Java collections like List and Arrays." }, { "code": null, "e": 93015, "s": 92906, "text": "DOM4J works with DOM, SAX, XPath, and XSLT. It can parse large XML documents with very low memory footprint." }, { "code": null, "e": 93151, "s": 93015, "text": "In order to use DOM4J parser, you should have dom4j-1.6.1.jar and jaxen.jar in your application's classpath. Download dom4j-1.6.1.zip.\n" }, { "code": null, "e": 93188, "s": 93151, "text": "You should use a DOM4J parser when −" }, { "code": null, "e": 93251, "s": 93188, "text": "You need to know a lot about the structure of an XML document." }, { "code": null, "e": 93314, "s": 93251, "text": "You need to know a lot about the structure of an XML document." }, { "code": null, "e": 93419, "s": 93314, "text": "You need to move parts of an XML document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 93524, "s": 93419, "text": "You need to move parts of an XML document around (you might want to sort certain elements, for example)." }, { "code": null, "e": 93591, "s": 93524, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 93658, "s": 93591, "text": "You need to use the information in an XML document more than once." }, { "code": null, "e": 93735, "s": 93658, "text": "You are a Java developer and want to leverage Java-optimized parsing of XML." }, { "code": null, "e": 93812, "s": 93735, "text": "You are a Java developer and want to leverage Java-optimized parsing of XML." }, { "code": null, "e": 94027, "s": 93812, "text": "When you parse an XML document with a DOM4J parser, you get the flexibility to get back a tree structure that contains all of the elements of your document without impacting the memory footprint of the application." }, { "code": null, "e": 94215, "s": 94027, "text": "DOM4J provides a variety of utility functions that you can use to examine the contents and structure of an XML document in case the document is well structured and its structure is known." }, { "code": null, "e": 94280, "s": 94215, "text": "DOM4J uses XPath expression to navigate through an XML document." }, { "code": null, "e": 94407, "s": 94280, "text": "DOM4J provides Java developers the flexibility and easy maintainablity of XML parsing code. It is a lightweight and quick API." }, { "code": null, "e": 94478, "s": 94407, "text": "DOM4J defines several Java classes. Here are the most common classes −" }, { "code": null, "e": 94579, "s": 94478, "text": "Document − Represents the entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 94680, "s": 94579, "text": "Document − Represents the entire XML document. A Document object is often referred to as a DOM tree." }, { "code": null, "e": 94812, "s": 94680, "text": "Element − Represents an XML element. Element object has methods to manipulate its child elements, text, attributes, and namespaces." }, { "code": null, "e": 94944, "s": 94812, "text": "Element − Represents an XML element. Element object has methods to manipulate its child elements, text, attributes, and namespaces." }, { "code": null, "e": 95089, "s": 94944, "text": "Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type." }, { "code": null, "e": 95234, "s": 95089, "text": "Attribute − Represents an attribute of an element. Attribute has method to get and set the value of attribute. It has parent and attribute type." }, { "code": null, "e": 95298, "s": 95234, "text": "Node − Represents Element, Attribute, or ProcessingInstruction." }, { "code": null, "e": 95362, "s": 95298, "text": "Node − Represents Element, Attribute, or ProcessingInstruction." }, { "code": null, "e": 95444, "s": 95362, "text": "When you are working with the DOM4J, there are several methods you'll use often −" }, { "code": null, "e": 95519, "s": 95444, "text": "SAXReader.read(xmlSource)() − Build the DOM4J document from an XML source." }, { "code": null, "e": 95594, "s": 95519, "text": "SAXReader.read(xmlSource)() − Build the DOM4J document from an XML source." }, { "code": null, "e": 95663, "s": 95594, "text": "Document.getRootElement() − Get the root element of an XML document." }, { "code": null, "e": 95732, "s": 95663, "text": "Document.getRootElement() − Get the root element of an XML document." }, { "code": null, "e": 95808, "s": 95732, "text": "Element.node(index) − Get the XML node at a particular index in an element." }, { "code": null, "e": 95884, "s": 95808, "text": "Element.node(index) − Get the XML node at a particular index in an element." }, { "code": null, "e": 95945, "s": 95884, "text": "Element.attributes() − Get all the attributes of an element." }, { "code": null, "e": 96006, "s": 95945, "text": "Element.attributes() − Get all the attributes of an element." }, { "code": null, "e": 96094, "s": 96006, "text": "Node.valueOf(@Name) − Get the values of an attribute with the given name of an element." }, { "code": null, "e": 96182, "s": 96094, "text": "Node.valueOf(@Name) − Get the values of an attribute with the given name of an element." }, { "code": null, "e": 96256, "s": 96182, "text": "Following are the steps used while parsing a document using DOM4J Parser." }, { "code": null, "e": 96285, "s": 96256, "text": "Import XML-related packages." }, { "code": null, "e": 96314, "s": 96285, "text": "Import XML-related packages." }, { "code": null, "e": 96334, "s": 96314, "text": "Create a SAXReader." }, { "code": null, "e": 96354, "s": 96334, "text": "Create a SAXReader." }, { "code": null, "e": 96395, "s": 96354, "text": "Create a Document from a file or stream." }, { "code": null, "e": 96436, "s": 96395, "text": "Create a Document from a file or stream." }, { "code": null, "e": 96516, "s": 96436, "text": "Get the required nodes using XPath Expression by calling document.selectNodes()" }, { "code": null, "e": 96596, "s": 96516, "text": "Get the required nodes using XPath Expression by calling document.selectNodes()" }, { "code": null, "e": 96622, "s": 96596, "text": "Extract the root element." }, { "code": null, "e": 96648, "s": 96622, "text": "Extract the root element." }, { "code": null, "e": 96680, "s": 96648, "text": "Iterate over the list of nodes." }, { "code": null, "e": 96712, "s": 96680, "text": "Iterate over the list of nodes." }, { "code": null, "e": 96732, "s": 96712, "text": "Examine attributes." }, { "code": null, "e": 96752, "s": 96732, "text": "Examine attributes." }, { "code": null, "e": 96774, "s": 96752, "text": "Examine sub-elements." }, { "code": null, "e": 96796, "s": 96774, "text": "Examine sub-elements." }, { "code": null, "e": 96854, "s": 96796, "text": "import java.io.*;\nimport java.util.*;\nimport org.dom4j.*;" }, { "code": null, "e": 96896, "s": 96854, "text": "SAXBuilder saxBuilder = new SAXBuilder();" }, { "code": null, "e": 97027, "s": 96896, "text": "File inputFile = new File(\"input.txt\");\nSAXBuilder saxBuilder = new SAXBuilder();\nDocument document = saxBuilder.build(inputFile);" }, { "code": null, "e": 97077, "s": 97027, "text": "Element classElement = document.getRootElement();" }, { "code": null, "e": 97134, "s": 97077, "text": "//returns specific attribute\nvalueOf(\"@attributeName\"); " }, { "code": null, "e": 97198, "s": 97134, "text": "//returns first child node\nselectSingleNode(\"subelementName\"); " }, { "code": null, "e": 97249, "s": 97198, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 97800, "s": 97249, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 99292, "s": 97800, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.util.List;\n\nimport org.dom4j.Document;\nimport org.dom4j.DocumentException;\nimport org.dom4j.Element;\nimport org.dom4j.Node;\nimport org.dom4j.io.SAXReader;\n\npublic class DOM4JParserDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXReader reader = new SAXReader();\n Document document = reader.read( inputFile );\n\n System.out.println(\"Root element :\" + document.getRootElement().getName());\n\n Element classElement = document.getRootElement();\n\n List<Node> nodes = document.selectNodes(\"/class/student\" );\n System.out.println(\"----------------------------\");\n \n for (Node node : nodes) {\n System.out.println(\"\\nCurrent Element :\"\n + node.getName());\n System.out.println(\"Student roll no : \" \n + node.valueOf(\"@rollno\") );\n System.out.println(\"First Name : \"\n + node.selectSingleNode(\"firstname\").getText());\n System.out.println(\"Last Name : \"\n + node.selectSingleNode(\"lastname\").getText());\n System.out.println(\"First Name : \"\n + node.selectSingleNode(\"nickname\").getText());\n System.out.println(\"Marks : \"\n + node.selectSingleNode(\"marks\").getText());\n }\n } catch (DocumentException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 99334, "s": 99292, "text": "This would produce the following result −" }, { "code": null, "e": 99721, "s": 99334, "text": "Root element :class\n----------------------------\n\nCurrent Element :student\nStudent roll no : \nFirst Name : dinkar\nLast Name : kad\nFirst Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : \nFirst Name : Vaneet\nLast Name : Gupta\nFirst Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : \nFirst Name : jasvir\nLast Name : singn\nFirst Name : jazz\nMarks : 90\n" }, { "code": null, "e": 99772, "s": 99721, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 100323, "s": 99772, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 101832, "s": 100323, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.util.List;\n\nimport org.dom4j.Document;\nimport org.dom4j.DocumentException;\nimport org.dom4j.Element;\nimport org.dom4j.Node;\nimport org.dom4j.io.SAXReader;\n\npublic class DOM4JQueryDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXReader reader = new SAXReader();\n Document document = reader.read( inputFile );\n\n System.out.println(\"Root element :\" + document.getRootElement().getName());\n\n Element classElement = document.getRootElement();\n\n List<Node> nodes = document.selectNodes(\"/class/student[@rollno = '493']\" );\n System.out.println(\"----------------------------\");\n \n for (Node node : nodes) {\n System.out.println(\"\\nCurrent Element :\" \n + node.getName());\n System.out.println(\"Student roll no : \" \n + node.valueOf(\"@rollno\") );\n System.out.println(\"First Name : \"\n + node.selectSingleNode(\"firstname\").getText());\n System.out.println(\"Last Name : \"\n + node.selectSingleNode(\"lastname\").getText());\n System.out.println(\"First Name : \"\n + node.selectSingleNode(\"nickname\").getText());\n System.out.println(\"Marks : \"\n + node.selectSingleNode(\"marks\").getText());\n }\n } catch (DocumentException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 101874, "s": 101832, "text": "This would produce the following result −" }, { "code": null, "e": 102039, "s": 101874, "text": "Root element :class\n----------------------------\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nFirst Name : vinni\nMarks : 95\n" }, { "code": null, "e": 102080, "s": 102039, "text": "Here is the XML that we need to create −" }, { "code": null, "e": 102300, "s": 102080, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 103540, "s": 102300, "text": "package com.tutorialspoint.xml;\n\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\n\nimport org.dom4j.Document;\nimport org.dom4j.DocumentHelper;\nimport org.dom4j.Element;\nimport org.dom4j.io.OutputFormat;\nimport org.dom4j.io.XMLWriter;\n\npublic class DOM4JCreateXMLDemo {\n\n public static void main(String[] args) {\n \n try {\n Document document = DocumentHelper.createDocument();\n Element root = document.addElement( \"cars\" );\n Element supercarElement = root.addElement(\"supercars\")\n .addAttribute(\"company\", \"Ferrai\");\n\n supercarElement.addElement(\"carname\")\n .addAttribute(\"type\", \"Ferrari 101\")\n .addText(\"Ferrari 101\");\n\n supercarElement.addElement(\"carname\")\n .addAttribute(\"type\", \"sports\")\n .addText(\"Ferrari 202\");\n\n // Pretty print the document to System.out\n OutputFormat format = OutputFormat.createPrettyPrint();\n XMLWriter writer;\n writer = new XMLWriter( System.out, format );\n writer.write( document );\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 103582, "s": 103540, "text": "This would produce the following result −" }, { "code": null, "e": 103803, "s": 103582, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 103844, "s": 103803, "text": "Here is the XML that we need to modify −" }, { "code": null, "e": 104395, "s": 103844, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 105979, "s": 104395, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.dom4j.Document;\nimport org.dom4j.DocumentException;\nimport org.dom4j.Element;\nimport org.dom4j.Node;\nimport org.dom4j.io.OutputFormat;\nimport org.dom4j.io.SAXReader;\nimport org.dom4j.io.XMLWriter;\n\npublic class DOM4jModifyXMLDemo {\n\n public static void main(String[] args) {\n \n try {\n File inputFile = new File(\"input.txt\");\n SAXReader reader = new SAXReader();\n Document document = reader.read( inputFile );\n\n Element classElement = document.getRootElement();\n\n List<Node> nodes = document.selectNodes(\"/class/student[@rollno = '493']\" );\n \n for (Node node : nodes) {\n Element element = (Element)node;\n Iterator<Element> iterator = element.elementIterator(\"marks\");\n\n while(iterator.hasNext()) {\n Element marksElement = (Element)iterator.next();\n marksElement.setText(\"80\");\n }\n }\n\n // Pretty print the document to System.out\n OutputFormat format = OutputFormat.createPrettyPrint();\n XMLWriter writer;\n writer = new XMLWriter( System.out, format );\n writer.write( document );\n } catch (DocumentException e) {\n e.printStackTrace();\n } catch (UnsupportedEncodingException e) { \n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 106021, "s": 105979, "text": "This would produce the following result −" }, { "code": null, "e": 106613, "s": 106021, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<class> \n <student rollno = \"393\"> \n <firstname>dinkar</firstname> \n <lastname>kad</lastname> \n <nickname>dinkar</nickname> \n <marks>85</marks> \n </student>\n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>vinni</nickname> \n <marks>80</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>jasvir</firstname> \n <lastname>singn</lastname> \n <nickname>jazz</nickname> \n <marks>90</marks> \n </student> \n</class>\n" }, { "code": null, "e": 106646, "s": 106613, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 106662, "s": 106646, "text": " Malhar Lathkar" }, { "code": null, "e": 106695, "s": 106662, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 106711, "s": 106695, "text": " Malhar Lathkar" }, { "code": null, "e": 106746, "s": 106711, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 106760, "s": 106746, "text": " Anadi Sharma" }, { "code": null, "e": 106794, "s": 106760, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 106808, "s": 106794, "text": " Tushar Kale" }, { "code": null, "e": 106845, "s": 106808, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 106860, "s": 106845, "text": " Monica Mittal" }, { "code": null, "e": 106893, "s": 106860, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 106912, "s": 106893, "text": " Arnab Chakraborty" }, { "code": null, "e": 106919, "s": 106912, "text": " Print" }, { "code": null, "e": 106930, "s": 106919, "text": " Add Notes" } ]
Conditional statements in JavaScript
There are three types of conditional statements in JavaScript − If statement − The if statement is used to execute code inside the if block only if the specific condition is met. If else statement − The If....Else statement is used to check only two conditions and execute different codes for each of them. If else if else statement − The if...else if...else statement is used for checking more than two conditions. Following is the code to implement conditional statements 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>Conditional statements in JavaScript</h1> <input type="text" class="numInput" /> <button class="Btn">CHECK</button><br /> <div class="result"></div> <h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let numInputEle = document.querySelector(".numInput"); BtnEle.addEventListener("click", () => { if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) { resEle.innerHTML = "The numbers is divisible by 2 and 3 both"; } else if (numInputEle.value % 3 === 0) { resEle.innerHTML = "The number is divisbly by 3"; } else if (numInputEle.value % 2 === 0) { resEle.innerHTML = "The numbers is divisible by 2"; } else { resEle.innerHTML = "The numbers isn't divisible by 2 or 3"; } }); </script> </body> </html> On entering a number and clicking on ‘CHECK’ button −
[ { "code": null, "e": 1126, "s": 1062, "text": "There are three types of conditional statements in JavaScript −" }, { "code": null, "e": 1241, "s": 1126, "text": "If statement − The if statement is used to execute code inside the if block only if the specific condition is met." }, { "code": null, "e": 1369, "s": 1241, "text": "If else statement − The If....Else statement is used to check only two conditions and execute different codes for each of them." }, { "code": null, "e": 1478, "s": 1369, "text": "If else if else statement − The if...else if...else statement is used for checking more than two conditions." }, { "code": null, "e": 1552, "s": 1478, "text": "Following is the code to implement conditional statements in JavaScript −" }, { "code": null, "e": 1563, "s": 1552, "text": " Live Demo" }, { "code": null, "e": 2868, "s": 1563, "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>Conditional statements in JavaScript</h1>\n<input type=\"text\" class=\"numInput\" />\n<button class=\"Btn\">CHECK</button><br />\n<div class=\"result\"></div>\n<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n let numInputEle = document.querySelector(\".numInput\");\n BtnEle.addEventListener(\"click\", () => {\n if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {\n resEle.innerHTML = \"The numbers is divisible by 2 and 3 both\";\n } else if (numInputEle.value % 3 === 0) {\n resEle.innerHTML = \"The number is divisbly by 3\";\n } else if (numInputEle.value % 2 === 0) {\n resEle.innerHTML = \"The numbers is divisible by 2\";\n } else {\n resEle.innerHTML = \"The numbers isn't divisible by 2 or 3\";\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2922, "s": 2868, "text": "On entering a number and clicking on ‘CHECK’ button −" } ]
Java regex program to verify whether a String contains at least one alphanumeric character.
Following regular expression matches a string that contains at least one alphanumeric characters − "^.*[a-zA-Z0-9]+.*$"; Where, ^.* Matches the string starting with zero or more (any) characters. ^.* Matches the string starting with zero or more (any) characters. [a-zA-Z0-9]+ Matches at least one alpha-numeric character. [a-zA-Z0-9]+ Matches at least one alpha-numeric character. .*$ Matches the string ending with zero or more (ant) characters. .*$ Matches the string ending with zero or more (ant) characters. Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a string"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression String regex = "^.*[a-zA-Z0-9]+.*$"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; if(matcher.matches()) { System.out.println("Given string is valid"); } else { System.out.println("Given string is not valid"); } } } Enter a string ###test123$$$ Given string is valid Enter a string ####$$$$ Given string is not valid Live Demo import java.util.Scanner; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a string"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression String regex = "^.*[a-zA-Z0-9]+.*$"; boolean result = input.matches(regex); if(result) { System.out.println("Valid match"); }else { System.out.println("In valid match"); } } } Enter a string ###test123$$$ Valid match Enter a string ####$$$$ In valid match
[ { "code": null, "e": 1161, "s": 1062, "text": "Following regular expression matches a string that contains at least one alphanumeric characters −" }, { "code": null, "e": 1183, "s": 1161, "text": "\"^.*[a-zA-Z0-9]+.*$\";" }, { "code": null, "e": 1190, "s": 1183, "text": "Where," }, { "code": null, "e": 1258, "s": 1190, "text": "^.* Matches the string starting with zero or more (any) characters." }, { "code": null, "e": 1326, "s": 1258, "text": "^.* Matches the string starting with zero or more (any) characters." }, { "code": null, "e": 1385, "s": 1326, "text": "[a-zA-Z0-9]+ Matches at least one alpha-numeric character." }, { "code": null, "e": 1444, "s": 1385, "text": "[a-zA-Z0-9]+ Matches at least one alpha-numeric character." }, { "code": null, "e": 1510, "s": 1444, "text": ".*$ Matches the string ending with zero or more (ant) characters." }, { "code": null, "e": 1576, "s": 1510, "text": ".*$ Matches the string ending with zero or more (ant) characters." }, { "code": null, "e": 1587, "s": 1576, "text": " Live Demo" }, { "code": null, "e": 2338, "s": 1587, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a string\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression\n String regex = \"^.*[a-zA-Z0-9]+.*$\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n int count = 0;\n if(matcher.matches()) {\n System.out.println(\"Given string is valid\");\n } else {\n System.out.println(\"Given string is not valid\");\n }\n }\n}" }, { "code": null, "e": 2389, "s": 2338, "text": "Enter a string\n###test123$$$\nGiven string is valid" }, { "code": null, "e": 2439, "s": 2389, "text": "Enter a string\n####$$$$\nGiven string is not valid" }, { "code": null, "e": 2450, "s": 2439, "text": " Live Demo" }, { "code": null, "e": 2953, "s": 2450, "text": "import java.util.Scanner;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a string\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression\n String regex = \"^.*[a-zA-Z0-9]+.*$\";\n boolean result = input.matches(regex);\n if(result) {\n System.out.println(\"Valid match\");\n }else {\n System.out.println(\"In valid match\");\n }\n }\n}" }, { "code": null, "e": 2994, "s": 2953, "text": "Enter a string\n###test123$$$\nValid match" }, { "code": null, "e": 3033, "s": 2994, "text": "Enter a string\n####$$$$\nIn valid match" } ]
Design and Analysis Bubble Sort
Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if necessary. When no exchanges are required, the file is sorted. This is the simplest technique among all sorting algorithms. Algorithm: Sequential-Bubble-Sort (A) fori← 1 to length [A] do for j ← length [A] down-to i +1 do if A[A] < A[j - 1] then Exchange A[j] ↔ A[j-1] voidbubbleSort(int numbers[], intarray_size) { inti, j, temp; for (i = (array_size - 1); i >= 0; i--) for (j = 1; j <= i; j++) if (numbers[j - 1] > numbers[j]) { temp = numbers[j-1]; numbers[j - 1] = numbers[j]; numbers[j] = temp; } } Here, the number of comparisons are 1 + 2 + 3 +...+ (n - 1) = n(n - 1)/2 = O(n2) Clearly, the graph shows the n2 nature of the bubble sort. In this algorithm, the number of comparison is irrespective of the data set, i.e. whether the provided input elements are in sorted order or in reverse order or at random. From the algorithm stated above, it is clear that bubble sort does not require extra memory. Unsorted list: 5 > 2 swap 5 > 1 swap 5 > 4 swap 5 > 3 swap 5 < 7 no swap 7 > 6 swap 2 > 1 swap 2 < 4 no swap 4 > 3 swap 4 < 5 no swap 5 < 6 no swap There is no change in 3rd, 4th, 5th and 6th iteration. Finally, the sorted list is 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2769, "s": 2599, "text": "Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if necessary. When no exchanges are required, the file is sorted." }, { "code": null, "e": 2830, "s": 2769, "text": "This is the simplest technique among all sorting algorithms." }, { "code": null, "e": 2990, "s": 2830, "text": "Algorithm: Sequential-Bubble-Sort (A) \nfori← 1 to length [A] do \nfor j ← length [A] down-to i +1 do \n if A[A] < A[j - 1] then \n Exchange A[j] ↔ A[j-1] \n" }, { "code": null, "e": 3284, "s": 2990, "text": "voidbubbleSort(int numbers[], intarray_size) { \n inti, j, temp; \n for (i = (array_size - 1); i >= 0; i--) \n for (j = 1; j <= i; j++) \n if (numbers[j - 1] > numbers[j]) { \n temp = numbers[j-1]; \n numbers[j - 1] = numbers[j]; \n numbers[j] = temp; \n } \n} \n" }, { "code": null, "e": 3320, "s": 3284, "text": "Here, the number of comparisons are" }, { "code": null, "e": 3365, "s": 3320, "text": "1 + 2 + 3 +...+ (n - 1) = n(n - 1)/2 = O(n2)" }, { "code": null, "e": 3424, "s": 3365, "text": "Clearly, the graph shows the n2 nature of the bubble sort." }, { "code": null, "e": 3596, "s": 3424, "text": "In this algorithm, the number of comparison is irrespective of the data set, i.e. whether the provided input elements are in sorted order or in reverse order or at random." }, { "code": null, "e": 3689, "s": 3596, "text": "From the algorithm stated above, it is clear that bubble sort does not require extra memory." }, { "code": null, "e": 3704, "s": 3689, "text": "Unsorted list:" }, { "code": null, "e": 3715, "s": 3704, "text": "5 > 2 swap" }, { "code": null, "e": 3726, "s": 3715, "text": "5 > 1 swap" }, { "code": null, "e": 3737, "s": 3726, "text": "5 > 4 swap" }, { "code": null, "e": 3748, "s": 3737, "text": "5 > 3 swap" }, { "code": null, "e": 3762, "s": 3748, "text": "5 < 7 no swap" }, { "code": null, "e": 3773, "s": 3762, "text": "7 > 6 swap" }, { "code": null, "e": 3784, "s": 3773, "text": "2 > 1 swap" }, { "code": null, "e": 3798, "s": 3784, "text": "2 < 4 no swap" }, { "code": null, "e": 3809, "s": 3798, "text": "4 > 3 swap" }, { "code": null, "e": 3823, "s": 3809, "text": "4 < 5 no swap" }, { "code": null, "e": 3837, "s": 3823, "text": "5 < 6 no swap" }, { "code": null, "e": 3892, "s": 3837, "text": "There is no change in 3rd, 4th, 5th and 6th iteration." }, { "code": null, "e": 3901, "s": 3892, "text": "Finally," }, { "code": null, "e": 3920, "s": 3901, "text": "the sorted list is" }, { "code": null, "e": 3955, "s": 3920, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 3974, "s": 3955, "text": " Arnab Chakraborty" }, { "code": null, "e": 4007, "s": 3974, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 4026, "s": 4007, "text": " Arnab Chakraborty" }, { "code": null, "e": 4059, "s": 4026, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 4078, "s": 4059, "text": " Arnab Chakraborty" }, { "code": null, "e": 4113, "s": 4078, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4126, "s": 4113, "text": " Manoj Kumar" }, { "code": null, "e": 4158, "s": 4126, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4171, "s": 4158, "text": " Zach Miller" }, { "code": null, "e": 4204, "s": 4171, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 4218, "s": 4204, "text": " Sasha Miller" }, { "code": null, "e": 4225, "s": 4218, "text": " Print" }, { "code": null, "e": 4236, "s": 4225, "text": " Add Notes" } ]
Right View of Binary Tree | Practice | GeeksforGeeks
Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side. Right view of following tree is 1 3 7 8. 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Example 1: Input: 1 / \ 3 2 Output: 1 2 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 10 30 60 Your Task: Just complete the function rightView() that takes node as parameter and returns the right view as a list. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 ≤ Number of nodes ≤ 105 1 ≤ Data of a node ≤ 105 0 binayshaw7777in 11 hours Simple Java Solution: class Solution{ //Function to return list containing elements of right view of binary tree. ArrayList<Integer> rightView(Node root) { ArrayList<Integer> list = new ArrayList<>(); RV(root, list, 0); return list; } public void RV(Node root, ArrayList<Integer> list, int level) { if (root == null) return; if (level == list.size()) list.add(root.data); RV(root.right, list, level+1); RV(root.left, list, level+1); } } 0 tarunkanade21 hours ago 0.17/1.16 Java Theta(n), Theta(w) ArrayList<Integer> rightView(Node root) { // Your code here ArrayList<Integer> list = new ArrayList<>(); if(root == null){ return list; } ArrayDeque<Node> q = new ArrayDeque<>(); int count; Node cur; q.offer(root); while(!q.isEmpty()){ count = q.size(); for(int i=0; i<count; i++){ cur = q.poll(); if(i == count-1){ list.add(cur.data); } if(cur.left != null) q.offer(cur.left); if(cur.right != null) q.offer(cur.right); } } return list; } 0 shubham211019973 days ago ArrayList<Integer> rightView(Node root) { ArrayList<Integer> arr=new ArrayList<Integer>(); if(root==null)return arr; Queue<Node>q=new LinkedList<>(); q.add(root); while(q.isEmpty()==false){ int size=q.size(); for(int i=0;i<size;i++){ Node curr=q.poll(); if(i==size-1){ arr.add(curr.data); } if(curr.left!=null)q.add(curr.left); if(curr.right!=null)q.add(curr.right); } } return arr; } 0 suyashsingh33 days ago Java space: O(h) solution ArrayList<Integer> rightView(Node node) { ArrayList<Integer> list=new ArrayList<Integer>(); max=0; if(node==null) return list; max=1; rightd(node,1, list); return list; } static int max=0; static void rightd(Node node,int level,ArrayList<Integer> list){ if(node==null) return; max=Math.max(level, max); if(level==max) {//list.size()<=level so ll add right node after that level ll be equal list.add(node.val); //don't need max param in this case max++; } rightd(node.right,level+1,list); rightd(node.left,level+1,list); } 0 anugrahlko5 days ago class Solution{ //Function to return list containing elements of right view of binary tree. static HashMap<Integer, ArrayList<Integer>> map; ArrayList<Integer> rightView(Node node) { //add code here. int level =0; map = new HashMap<Integer, ArrayList<Integer>>(); ArrayList<Integer> res = new ArrayList<Integer>(); getMap(node, level); int i=0; while(map.containsKey(i)){ ArrayList<Integer> l = map.get(i); int mostRightElementIndex = l.size()-1; int mostRightElement = l.get(mostRightElementIndex); res.add(mostRightElement); i++; } return res; } void getMap(Node node, Integer level){ if(node==null) return; if(map.containsKey(level)){ ArrayList<Integer> list = map.get(level); list.add(node.data); map.put(level,list); }else{ ArrayList<Integer> list = new ArrayList<Integer>(); list.add(node.data); map.put(level,list); } getMap(node.left, level+1); getMap(node.right, level+1); } } +1 jainmuskan5652 weeks ago vector<int> v; void fxn(Node * node,int level){ if(node==NULL){ return; } if(v.size()<= level){ v.push_back(node->data); } fxn(node->right,level+1); fxn(node->left,level+1); } vector<int> rightView(Node *root) { // Your Code here v.clear(); fxn(root, 0); return v; } 0 bheniavedant2 weeks ago #User function Template for python3 '''# Node Class:class Node: def init(self,val): self.data = val self.left = None self.right = None'''class Solution: #Function to return list containing elements of right view of binary tree. def rightView(self,root): # code here level = [] result = [] if root is None: return q = [root] while len(q)!= 0: for node in q: if node.left : level.append(node.left) if node.right: level.append(node.right) result.append(node.data) q = level level = [] return result 0 rohanmeher1642 weeks ago //Java solution class Solution{ //Function to return list containing elements of right view of binary tree. ArrayList<Integer> rightView(Node node) { ArrayList<Integer> list=new ArrayList<Integer>(); helper(node,list); return list; } void helper(Node root,ArrayList<Integer> list) { if(root==null) return; Queue<Node> q=new LinkedList<Node>(); q.add(root); while(!q.isEmpty()) { int n=q.size(); for(int i=1;i<=n;i++) { Node t=q.poll(); if(i==n) list.add(t.data); if(t.left!=null) q.add(t.left); if(t.right!=null) q.add(t.right); } } }} +1 deathcloud This comment was deleted. +1 hanumanmanyam8373 weeks ago class Solution{ void left(Node root,ArrayList<Integer>res,int level) { if(root==null) { return; } if(res.size()==level) { res.add(root.data); } left(root.left,res,level+1); left(root.right,res,level+1); } //Function to return list containing elements of right view of binary tree. ArrayList<Integer> rightView(Node node) { //add code here. if(node!=null) { rightView(node.left); rightView(node.right); Node temp=node.left; node.left=node.right; node.right=temp; } Solution s= new Solution(); ArrayList<Integer>res=new ArrayList<>(); s.left(node,res,0); return res; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 371, "s": 238, "text": "Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side." }, { "code": null, "e": 412, "s": 371, "text": "Right view of following tree is 1 3 7 8." }, { "code": null, "e": 508, "s": 412, "text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\\n 8" }, { "code": null, "e": 519, "s": 508, "text": "Example 1:" }, { "code": null, "e": 571, "s": 519, "text": "Input:\n 1\n / \\\n 3 2\nOutput: 1 2\n" }, { "code": null, "e": 582, "s": 571, "text": "Example 2:" }, { "code": null, "e": 652, "s": 582, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n40 60 \nOutput: 10 30 60\n" }, { "code": null, "e": 770, "s": 652, "text": "Your Task:\nJust complete the function rightView() that takes node as parameter and returns the right view as a list. " }, { "code": null, "e": 851, "s": 770, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 915, "s": 851, "text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105" }, { "code": null, "e": 917, "s": 915, "text": "0" }, { "code": null, "e": 942, "s": 917, "text": "binayshaw7777in 11 hours" }, { "code": null, "e": 964, "s": 942, "text": "Simple Java Solution:" }, { "code": null, "e": 1454, "s": 964, "text": "class Solution{\n //Function to return list containing elements of right view of binary tree.\n ArrayList<Integer> rightView(Node root) {\n ArrayList<Integer> list = new ArrayList<>();\n RV(root, list, 0);\n return list;\n }\n \n public void RV(Node root, ArrayList<Integer> list, int level) {\n if (root == null) return;\n if (level == list.size()) list.add(root.data);\n RV(root.right, list, level+1);\n RV(root.left, list, level+1);\n }\n}" }, { "code": null, "e": 1456, "s": 1454, "text": "0" }, { "code": null, "e": 1480, "s": 1456, "text": "tarunkanade21 hours ago" }, { "code": null, "e": 1514, "s": 1480, "text": "0.17/1.16 Java Theta(n), Theta(w)" }, { "code": null, "e": 2216, "s": 1514, "text": "ArrayList<Integer> rightView(Node root)\n {\n // Your code here\n ArrayList<Integer> list = new ArrayList<>();\n \n if(root == null){\n return list;\n }\n \n ArrayDeque<Node> q = new ArrayDeque<>();\n int count;\n Node cur;\n \n q.offer(root);\n \n while(!q.isEmpty()){\n count = q.size();\n \n for(int i=0; i<count; i++){\n cur = q.poll();\n if(i == count-1){\n list.add(cur.data);\n }\n \n if(cur.left != null) q.offer(cur.left);\n if(cur.right != null) q.offer(cur.right);\n }\n }\n \n return list;\n }" }, { "code": null, "e": 2218, "s": 2216, "text": "0" }, { "code": null, "e": 2244, "s": 2218, "text": "shubham211019973 days ago" }, { "code": null, "e": 2767, "s": 2244, "text": " ArrayList<Integer> rightView(Node root) {\n ArrayList<Integer> arr=new ArrayList<Integer>();\n if(root==null)return arr;\n Queue<Node>q=new LinkedList<>();\n q.add(root);\n while(q.isEmpty()==false){\n int size=q.size();\n for(int i=0;i<size;i++){\n Node curr=q.poll();\n if(i==size-1){\n arr.add(curr.data);\n }\n if(curr.left!=null)q.add(curr.left);\n if(curr.right!=null)q.add(curr.right);\n }\n }\n return arr;\n }" }, { "code": null, "e": 2769, "s": 2767, "text": "0" }, { "code": null, "e": 2792, "s": 2769, "text": "suyashsingh33 days ago" }, { "code": null, "e": 2819, "s": 2792, "text": "Java space: O(h) solution " }, { "code": null, "e": 3376, "s": 2819, "text": " ArrayList<Integer> rightView(Node node) {\n ArrayList<Integer> list=new ArrayList<Integer>();\n max=0;\n if(node==null) return list;\n max=1;\n rightd(node,1, list);\n \n return list;\n \n}\nstatic int max=0;\nstatic void rightd(Node node,int level,ArrayList<Integer> list){\n if(node==null) return;\n max=Math.max(level, max);\n if(level==max) {//list.size()<=level so ll add right node after that level ll be equal \n list.add(node.val); //don't need max param in this case\n \n max++;\n }\n \n\n \n rightd(node.right,level+1,list);\n rightd(node.left,level+1,list);\n \n \n}" }, { "code": null, "e": 3380, "s": 3378, "text": "0" }, { "code": null, "e": 3401, "s": 3380, "text": "anugrahlko5 days ago" }, { "code": null, "e": 4572, "s": 3401, "text": "class Solution{\n //Function to return list containing elements of right view of binary tree.\n static HashMap<Integer, ArrayList<Integer>> map;\n ArrayList<Integer> rightView(Node node) {\n //add code here.\n int level =0;\n map = new HashMap<Integer, ArrayList<Integer>>();\n ArrayList<Integer> res = new ArrayList<Integer>();\n getMap(node, level);\n int i=0;\n while(map.containsKey(i)){\n ArrayList<Integer> l = map.get(i);\n int mostRightElementIndex = l.size()-1;\n int mostRightElement = l.get(mostRightElementIndex);\n res.add(mostRightElement);\n i++;\n }\n return res;\n \n }\n void getMap(Node node, Integer level){\n if(node==null) return;\n if(map.containsKey(level)){\n ArrayList<Integer> list = map.get(level);\n list.add(node.data);\n map.put(level,list);\n }else{\n ArrayList<Integer> list = new ArrayList<Integer>();\n list.add(node.data);\n map.put(level,list);\n }\n getMap(node.left, level+1);\n getMap(node.right, level+1);\n }\n}" }, { "code": null, "e": 4575, "s": 4572, "text": "+1" }, { "code": null, "e": 4600, "s": 4575, "text": "jainmuskan5652 weeks ago" }, { "code": null, "e": 4954, "s": 4600, "text": " vector<int> v; void fxn(Node * node,int level){ if(node==NULL){ return; } if(v.size()<= level){ v.push_back(node->data); } fxn(node->right,level+1); fxn(node->left,level+1); } vector<int> rightView(Node *root) { // Your Code here v.clear(); fxn(root, 0); return v; }" }, { "code": null, "e": 4956, "s": 4954, "text": "0" }, { "code": null, "e": 4980, "s": 4956, "text": "bheniavedant2 weeks ago" }, { "code": null, "e": 5016, "s": 4980, "text": "#User function Template for python3" }, { "code": null, "e": 5661, "s": 5018, "text": "'''# Node Class:class Node: def init(self,val): self.data = val self.left = None self.right = None'''class Solution: #Function to return list containing elements of right view of binary tree. def rightView(self,root): # code here level = [] result = [] if root is None: return q = [root] while len(q)!= 0: for node in q: if node.left : level.append(node.left) if node.right: level.append(node.right) result.append(node.data) q = level level = []" }, { "code": null, "e": 5695, "s": 5661, "text": " return result " }, { "code": null, "e": 5697, "s": 5695, "text": "0" }, { "code": null, "e": 5722, "s": 5697, "text": "rohanmeher1642 weeks ago" }, { "code": null, "e": 5738, "s": 5722, "text": "//Java solution" }, { "code": null, "e": 6448, "s": 5740, "text": "class Solution{ //Function to return list containing elements of right view of binary tree. ArrayList<Integer> rightView(Node node) { ArrayList<Integer> list=new ArrayList<Integer>(); helper(node,list); return list; } void helper(Node root,ArrayList<Integer> list) { if(root==null) return; Queue<Node> q=new LinkedList<Node>(); q.add(root); while(!q.isEmpty()) { int n=q.size(); for(int i=1;i<=n;i++) { Node t=q.poll(); if(i==n) list.add(t.data); if(t.left!=null) q.add(t.left); if(t.right!=null) q.add(t.right); } } }}" }, { "code": null, "e": 6451, "s": 6448, "text": "+1" }, { "code": null, "e": 6462, "s": 6451, "text": "deathcloud" }, { "code": null, "e": 6488, "s": 6462, "text": "This comment was deleted." }, { "code": null, "e": 6491, "s": 6488, "text": "+1" }, { "code": null, "e": 6519, "s": 6491, "text": "hanumanmanyam8373 weeks ago" }, { "code": null, "e": 7342, "s": 6519, "text": "class Solution{\n void left(Node root,ArrayList<Integer>res,int level)\n {\n if(root==null)\n {\n return;\n }\n if(res.size()==level)\n {\n res.add(root.data);\n }\n left(root.left,res,level+1);\n left(root.right,res,level+1);\n }\n //Function to return list containing elements of right view of binary tree.\n ArrayList<Integer> rightView(Node node) {\n //add code here.\n \n if(node!=null)\n {\n rightView(node.left);\n rightView(node.right);\n Node temp=node.left;\n node.left=node.right;\n node.right=temp;\n }\n Solution s= new Solution();\n ArrayList<Integer>res=new ArrayList<>();\n s.left(node,res,0);\n return res;\n \n }\n}" }, { "code": null, "e": 7488, "s": 7342, "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": 7524, "s": 7488, "text": " Login to access your submissions. " }, { "code": null, "e": 7534, "s": 7524, "text": "\nProblem\n" }, { "code": null, "e": 7544, "s": 7534, "text": "\nContest\n" }, { "code": null, "e": 7607, "s": 7544, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7755, "s": 7607, "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": 7963, "s": 7755, "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": 8069, "s": 7963, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java.lang.Package class in Java
15 Jul, 2017 Java 2 added a class called Package that encapsulates version data associated with a package. Package version information is becoming more important because of the proliferation of packages and because a java program may need to know what version of a package is available.This versioning information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes. It extends class Object and implements AnnotatedElement. Methods: getAnnotation(Class annotationClass): Returns this element’s annotation for the specified type if such an annotation is present, else null.Syntax: public A getAnnotation(Class annotationClass) Returns: this element's annotation for the specified annotation type if present on this element, else null. Exception: NullPointerException - if the given annotation class is null. // Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100 Annotation[] getAnnotations(): Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) Annotation[] getDeclaredAnnotations(): Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output: Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) String getImplementationTitle(): Return the title of this package.Syntax: public String getImplementationTitle() Returns: the title of the implementation, null is returned if it is not known. Exception: NA String getImplementationVersion(): Return the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package.Syntax: public String getImplementationVersion() Returns: the version of the implementation, null is returned if it is not known. Exception: NA String getImplementationVendor(): Returns the name of the organization, vendor or company that provided this implementation.Syntax: public String getImplementationVendor(). Returns: the vendor that implemented this package. Exception: NA. String getName(): Return the name of this package.Syntax: public String getName() Returns: The fully-qualified name of this package as defined in section 6.5.3 of The JavaTM Language Specification, for example, java.lang. Exception: NA // Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }}Output:sun.reflect Java Runtime Environment Oracle Corporation 1.8.0_121 static Package getPackage(String name): Find a package by name in the callers ClassLoader instance. The callers ClassLoader instance is used to find the package instance corresponding to the named class. If the callers ClassLoader instance is null then the set of packages loaded by the system ClassLoader instance is searched to find the named package.Syntax: public static Package getPackage(String name) Returns: the package of the requested name. It may be null if no package information is available from the archive or codebase. Exception: NA static Package[] getPackages(): Get all the packages currently known for the caller’s ClassLoader instance. Those packages correspond to classes loaded via or accessible by name to that ClassLoader instance. If the caller’s ClassLoader instance is the bootstrap ClassLoader instance, which may be represented by null in some implementations, only packages corresponding to classes loaded by the bootstrap ClassLoader instance will be returned.Syntax: public static Package[] getPackages() Returns: a new array of packages known to the callers ClassLoader instance. An zero length array is returned if none are known. Exception: NA // Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage("java.lang"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }}Output:java.lang sun.reflect String getSpecificationTitle(): Return the title of the specification that this package implements.Syntax: public String getSpecificationTitle() Returns: the specification title, null is returned if it is not known. exception: NA. String getSpecificationVersion(): Returns the version number of the specification that this package implements. This version string must be a sequence of nonnegative decimal integers separated by “.”‘s and may have leading zeros. When version strings are compared the most significant numbers are compared.Syntax: public String getSpecificationVersion(). Returns: the specification version, null is returned if it is not known. Exception: NA. String getSpecificationVendor(): Return the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package.Syntax: public String getSpecificationVendor() Returns: the specification vendor, null is returned if it is not known. Exception: NA. int hashCode(): Return the hash code computed from the package name.Syntax: Return the hash code computed from the package name. Exception: NA Returns: the hash code. // Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }}Output:685414683 Java Platform API Specification Oracle Corporation 1.8 boolean isCompatibleWith(String desired): Compare this package’s specification version with a desired version. It returns true if this packages specification version number is greater than or equal to the desired version number.Syntax: public boolean isCompatibleWith(String desired). Returns: true if this package's version number is greater than or equal to the desired version number Exception: NumberFormatException - if the desired or current version is not of the correct dotted form. boolean isSealed(): Returns true if this package is sealed.Syntax: public boolean isSealed() Returns: true if the package is sealed, false otherwise. Exception: NA boolean isSealed(URL url): Returns true if this package is sealed with respect to the specified code source url.Syntax: public boolean isSealed(URL url) Returns: true if this package is sealed with respect to url Exception: NA String toString(): Returns the string representation of this Package. Its value is the string “package ” and the package name. If the package title is defined it is appended. If the package version is defined it is appended.Syntax: public String toString() Returns: the string representation of the package. Exception: NA // java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage("java.lang"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith("1.0")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL("https://www.youtube.com/"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }}Output:true false false package java.lang, Java Platform API Specification, version 1.8 getAnnotation(Class annotationClass): Returns this element’s annotation for the specified type if such an annotation is present, else null.Syntax: public A getAnnotation(Class annotationClass) Returns: this element's annotation for the specified annotation type if present on this element, else null. Exception: NullPointerException - if the given annotation class is null. // Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100 Syntax: public A getAnnotation(Class annotationClass) Returns: this element's annotation for the specified annotation type if present on this element, else null. Exception: NullPointerException - if the given annotation class is null. // Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }} Output: Gfg Demo Annotation 100 Annotation[] getAnnotations(): Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }} Output: Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) Annotation[] getDeclaredAnnotations(): Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output: Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) Syntax: public Annotation[] getDeclaredAnnotations(). Returns: All annotations directly present on this element. Exception: NA. // java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = " Gfg Demo Annotation", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod("gfg"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + " " + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }} Output: Gfg Demo Annotation 100 @Demo(str= Gfg Demo Annotation, val=100) String getImplementationTitle(): Return the title of this package.Syntax: public String getImplementationTitle() Returns: the title of the implementation, null is returned if it is not known. Exception: NA Syntax: public String getImplementationTitle() Returns: the title of the implementation, null is returned if it is not known. Exception: NA String getImplementationVersion(): Return the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package.Syntax: public String getImplementationVersion() Returns: the version of the implementation, null is returned if it is not known. Exception: NA Syntax: public String getImplementationVersion() Returns: the version of the implementation, null is returned if it is not known. Exception: NA String getImplementationVendor(): Returns the name of the organization, vendor or company that provided this implementation.Syntax: public String getImplementationVendor(). Returns: the vendor that implemented this package. Exception: NA. Syntax: public String getImplementationVendor(). Returns: the vendor that implemented this package. Exception: NA. String getName(): Return the name of this package.Syntax: public String getName() Returns: The fully-qualified name of this package as defined in section 6.5.3 of The JavaTM Language Specification, for example, java.lang. Exception: NA // Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }}Output:sun.reflect Java Runtime Environment Oracle Corporation 1.8.0_121 Syntax: public String getName() Returns: The fully-qualified name of this package as defined in section 6.5.3 of The JavaTM Language Specification, for example, java.lang. Exception: NA // Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }} Output: sun.reflect Java Runtime Environment Oracle Corporation 1.8.0_121 static Package getPackage(String name): Find a package by name in the callers ClassLoader instance. The callers ClassLoader instance is used to find the package instance corresponding to the named class. If the callers ClassLoader instance is null then the set of packages loaded by the system ClassLoader instance is searched to find the named package.Syntax: public static Package getPackage(String name) Returns: the package of the requested name. It may be null if no package information is available from the archive or codebase. Exception: NA Syntax: public static Package getPackage(String name) Returns: the package of the requested name. It may be null if no package information is available from the archive or codebase. Exception: NA static Package[] getPackages(): Get all the packages currently known for the caller’s ClassLoader instance. Those packages correspond to classes loaded via or accessible by name to that ClassLoader instance. If the caller’s ClassLoader instance is the bootstrap ClassLoader instance, which may be represented by null in some implementations, only packages corresponding to classes loaded by the bootstrap ClassLoader instance will be returned.Syntax: public static Package[] getPackages() Returns: a new array of packages known to the callers ClassLoader instance. An zero length array is returned if none are known. Exception: NA // Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage("java.lang"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }}Output:java.lang sun.reflect Syntax: public static Package[] getPackages() Returns: a new array of packages known to the callers ClassLoader instance. An zero length array is returned if none are known. Exception: NA // Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage("java.lang"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }} Output: java.lang sun.reflect String getSpecificationTitle(): Return the title of the specification that this package implements.Syntax: public String getSpecificationTitle() Returns: the specification title, null is returned if it is not known. exception: NA. Syntax: public String getSpecificationTitle() Returns: the specification title, null is returned if it is not known. exception: NA. String getSpecificationVersion(): Returns the version number of the specification that this package implements. This version string must be a sequence of nonnegative decimal integers separated by “.”‘s and may have leading zeros. When version strings are compared the most significant numbers are compared.Syntax: public String getSpecificationVersion(). Returns: the specification version, null is returned if it is not known. Exception: NA. Syntax: public String getSpecificationVersion(). Returns: the specification version, null is returned if it is not known. Exception: NA. String getSpecificationVendor(): Return the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package.Syntax: public String getSpecificationVendor() Returns: the specification vendor, null is returned if it is not known. Exception: NA. Syntax: public String getSpecificationVendor() Returns: the specification vendor, null is returned if it is not known. Exception: NA. int hashCode(): Return the hash code computed from the package name.Syntax: Return the hash code computed from the package name. Exception: NA Returns: the hash code. // Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }}Output:685414683 Java Platform API Specification Oracle Corporation 1.8 Syntax: Return the hash code computed from the package name. Exception: NA Returns: the hash code. // Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }} Output: 685414683 Java Platform API Specification Oracle Corporation 1.8 boolean isCompatibleWith(String desired): Compare this package’s specification version with a desired version. It returns true if this packages specification version number is greater than or equal to the desired version number.Syntax: public boolean isCompatibleWith(String desired). Returns: true if this package's version number is greater than or equal to the desired version number Exception: NumberFormatException - if the desired or current version is not of the correct dotted form. Syntax: public boolean isCompatibleWith(String desired). Returns: true if this package's version number is greater than or equal to the desired version number Exception: NumberFormatException - if the desired or current version is not of the correct dotted form. boolean isSealed(): Returns true if this package is sealed.Syntax: public boolean isSealed() Returns: true if the package is sealed, false otherwise. Exception: NA Syntax: public boolean isSealed() Returns: true if the package is sealed, false otherwise. Exception: NA boolean isSealed(URL url): Returns true if this package is sealed with respect to the specified code source url.Syntax: public boolean isSealed(URL url) Returns: true if this package is sealed with respect to url Exception: NA Syntax: public boolean isSealed(URL url) Returns: true if this package is sealed with respect to url Exception: NA String toString(): Returns the string representation of this Package. Its value is the string “package ” and the package name. If the package title is defined it is appended. If the package version is defined it is appended.Syntax: public String toString() Returns: the string representation of the package. Exception: NA // java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage("java.lang"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith("1.0")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL("https://www.youtube.com/"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }}Output:true false false package java.lang, Java Platform API Specification, version 1.8 Syntax: public String toString() Returns: the string representation of the package. Exception: NA // java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage("java.lang"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith("1.0")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL("https://www.youtube.com/"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }} Output: true false false package java.lang, Java Platform API Specification, version 1.8 This article is contributed by Abhishek Verma. 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. Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2017" }, { "code": null, "e": 575, "s": 52, "text": "Java 2 added a class called Package that encapsulates version data associated with a package. Package version information is becoming more important because of the proliferation of packages and because a java program may need to know what version of a package is available.This versioning information is retrieved and made available by the ClassLoader instance that loaded the class(es). Typically, it is stored in the manifest that is distributed with the classes. It extends class Object and implements AnnotatedElement." }, { "code": null, "e": 584, "s": 575, "text": "Methods:" }, { "code": null, "e": 13033, "s": 584, "text": "getAnnotation(Class annotationClass): Returns this element’s annotation for the specified type if such an annotation is present, else null.Syntax: public A getAnnotation(Class annotationClass)\nReturns: this element's annotation for the specified \nannotation type if present on this element, else null.\nException: NullPointerException - if the given annotation class is null.\n// Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100\nAnnotation[] getAnnotations(): Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n// Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\nAnnotation[] getDeclaredAnnotations(): Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n// java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output: Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\nString getImplementationTitle(): Return the title of this package.Syntax: public String getImplementationTitle()\nReturns: the title of the implementation, null is returned if it is not known.\nException: NA\nString getImplementationVersion(): Return the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package.Syntax: public String getImplementationVersion()\nReturns: the version of the implementation, null is returned if it is not known.\nException: NA\nString getImplementationVendor(): Returns the name of the organization, vendor or company that provided this implementation.Syntax: public String getImplementationVendor().\nReturns: the vendor that implemented this package.\nException: NA.\nString getName(): Return the name of this package.Syntax: public String getName()\nReturns: The fully-qualified name of this package as defined\n in section 6.5.3 of The JavaTM Language Specification, for example, java.lang.\nException: NA\n// Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }}Output:sun.reflect\nJava Runtime Environment\nOracle Corporation\n1.8.0_121\nstatic Package getPackage(String name): Find a package by name in the callers ClassLoader instance. The callers ClassLoader instance is used to find the package instance corresponding to the named class. If the callers ClassLoader instance is null then the set of packages loaded by the system ClassLoader instance is searched to find the named package.Syntax: public static Package getPackage(String name)\nReturns: the package of the requested name. It may \nbe null if no package information is available from the archive or \ncodebase.\nException: NA\nstatic Package[] getPackages(): Get all the packages currently known for the caller’s ClassLoader instance. Those packages correspond to classes loaded via or accessible by name to that ClassLoader instance. If the caller’s ClassLoader instance is the bootstrap ClassLoader instance, which may be represented by null in some implementations, only packages corresponding to classes loaded by the bootstrap ClassLoader instance will be returned.Syntax: public static Package[] getPackages()\nReturns: a new array of packages known to the callers \nClassLoader instance. An zero length array is returned if none are known.\nException: NA\n// Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage(\"java.lang\"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }}Output:java.lang\nsun.reflect\nString getSpecificationTitle(): Return the title of the specification that this package implements.Syntax: public String getSpecificationTitle()\nReturns: the specification title, null is returned \nif it is not known.\nexception: NA.\nString getSpecificationVersion(): Returns the version number of the specification that this package implements. This version string must be a sequence of nonnegative decimal integers separated by “.”‘s and may have leading zeros. When version strings are compared the most significant numbers are compared.Syntax: public String getSpecificationVersion().\nReturns: the specification version, null is returned \nif it is not known.\nException: NA.\nString getSpecificationVendor(): Return the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package.Syntax: public String getSpecificationVendor()\nReturns: the specification vendor, null is returned\n if it is not known.\nException: NA.\nint hashCode(): Return the hash code computed from the package name.Syntax: Return the hash code computed from the package name.\nException: NA\nReturns: the hash code.\n// Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }}Output:685414683\nJava Platform API Specification\nOracle Corporation\n1.8\nboolean isCompatibleWith(String desired): Compare this package’s specification version with a desired version. It returns true if this packages specification version number is greater than or equal to the desired version number.Syntax: public boolean isCompatibleWith(String desired).\nReturns: true if this package's version number is \ngreater than or equal to the desired version number\nException: \nNumberFormatException - if the desired or current version is not \nof the correct dotted form.\nboolean isSealed(): Returns true if this package is sealed.Syntax: public boolean isSealed()\nReturns: true if the package is sealed, false otherwise.\nException: NA\nboolean isSealed(URL url): Returns true if this package is sealed with respect to the specified code source url.Syntax: public boolean isSealed(URL url)\nReturns: true if this package is sealed with respect to url\nException: NA\nString toString(): Returns the string representation of this Package. Its value is the string “package ” and the package name. If the package title is defined it is appended. If the package version is defined it is appended.Syntax: public String toString()\nReturns: the string representation of the package.\nException: NA\n// java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage(\"java.lang\"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith(\"1.0\")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL(\"https://www.youtube.com/\"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }}Output:true\nfalse\nfalse\npackage java.lang, Java Platform API Specification, version 1.8\n" }, { "code": null, "e": 14393, "s": 13033, "text": "getAnnotation(Class annotationClass): Returns this element’s annotation for the specified type if such an annotation is present, else null.Syntax: public A getAnnotation(Class annotationClass)\nReturns: this element's annotation for the specified \nannotation type if present on this element, else null.\nException: NullPointerException - if the given annotation class is null.\n// Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100\n" }, { "code": null, "e": 14631, "s": 14393, "text": "Syntax: public A getAnnotation(Class annotationClass)\nReturns: this element's annotation for the specified \nannotation type if present on this element, else null.\nException: NullPointerException - if the given annotation class is null.\n" }, { "code": "// Java code illustrating getAnnotation() method import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); } public static void main(String args[]) throws Exception { gfg(); }}", "e": 15584, "s": 14631, "text": null }, { "code": null, "e": 15592, "s": 15584, "text": "Output:" }, { "code": null, "e": 15617, "s": 15592, "text": "Gfg Demo Annotation 100\n" }, { "code": null, "e": 17265, "s": 15617, "text": "Annotation[] getAnnotations(): Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n// Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output:Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\n" }, { "code": null, "e": 17394, "s": 17265, "text": "Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n" }, { "code": "// Java code illustrating getAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}", "e": 18565, "s": 17394, "text": null }, { "code": null, "e": 18573, "s": 18565, "text": "Output:" }, { "code": null, "e": 18639, "s": 18573, "text": "Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\n" }, { "code": null, "e": 20431, "s": 18639, "text": "Annotation[] getDeclaredAnnotations(): Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n// java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}Output: Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\n" }, { "code": null, "e": 20560, "s": 20431, "text": "Syntax: public Annotation[] getDeclaredAnnotations().\nReturns: All annotations directly present on this element.\nException: NA.\n" }, { "code": "// java code illustrating getDeclaredAnnotation() methodimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method; // declare a annotation type@Retention(RetentionPolicy.RUNTIME)@interface Demo { String str(); int val();} public class PackageDemo { // setting values for the annotation @Demo(str = \" Gfg Demo Annotation\", val = 100) // a method to call in the main public static void gfg() throws NoSuchMethodException { PackageDemo ob = new PackageDemo(); Class c = ob.getClass(); // get the method example Method m = c.getMethod(\"gfg\"); // get the annotation for class Demo Demo annotation = m.getAnnotation(Demo.class); // checking the annotation System.out.println(annotation.str() + \" \" + annotation.val()); Annotation[] gfg_ann = m.getDeclaredAnnotations(); for(int i = 0; i < gfg_ann.length; i++) { System.out.println(gfg_ann[i]); } } public static void main(String args[]) throws Exception { gfg(); }}", "e": 21741, "s": 20560, "text": null }, { "code": null, "e": 21749, "s": 21741, "text": "Output:" }, { "code": null, "e": 21816, "s": 21749, "text": " Gfg Demo Annotation 100\n@Demo(str= Gfg Demo Annotation, val=100)\n" }, { "code": null, "e": 22023, "s": 21816, "text": "String getImplementationTitle(): Return the title of this package.Syntax: public String getImplementationTitle()\nReturns: the title of the implementation, null is returned if it is not known.\nException: NA\n" }, { "code": null, "e": 22164, "s": 22023, "text": "Syntax: public String getImplementationTitle()\nReturns: the title of the implementation, null is returned if it is not known.\nException: NA\n" }, { "code": null, "e": 22670, "s": 22164, "text": "String getImplementationVersion(): Return the version of this implementation. It consists of any string assigned by the vendor of this implementation and does not have any particular syntax specified or expected by the Java runtime. It may be compared for equality with other package version strings used for this implementation by this vendor for this package.Syntax: public String getImplementationVersion()\nReturns: the version of the implementation, null is returned if it is not known.\nException: NA\n" }, { "code": null, "e": 22815, "s": 22670, "text": "Syntax: public String getImplementationVersion()\nReturns: the version of the implementation, null is returned if it is not known.\nException: NA\n" }, { "code": null, "e": 23055, "s": 22815, "text": "String getImplementationVendor(): Returns the name of the organization, vendor or company that provided this implementation.Syntax: public String getImplementationVendor().\nReturns: the vendor that implemented this package.\nException: NA.\n" }, { "code": null, "e": 23171, "s": 23055, "text": "Syntax: public String getImplementationVendor().\nReturns: the vendor that implemented this package.\nException: NA.\n" }, { "code": null, "e": 24286, "s": 23171, "text": "String getName(): Return the name of this package.Syntax: public String getName()\nReturns: The fully-qualified name of this package as defined\n in section 6.5.3 of The JavaTM Language Specification, for example, java.lang.\nException: NA\n// Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }}Output:sun.reflect\nJava Runtime Environment\nOracle Corporation\n1.8.0_121\n" }, { "code": null, "e": 24474, "s": 24286, "text": "Syntax: public String getName()\nReturns: The fully-qualified name of this package as defined\n in section 6.5.3 of The JavaTM Language Specification, for example, java.lang.\nException: NA\n" }, { "code": "// Java code illustrating getName(), getImplementationTitle()// and getImplementationVendor() and getImplementationVersion()// methodsclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].getName()); // checking title of this implementation System.out.println(pkgs[i].getImplementationTitle()); // checking the vendor System.out.println(pkgs[i].getImplementationVendor()); // version of this implementation System.out.println(pkgs[i].getImplementationVersion()); } }}", "e": 25279, "s": 24474, "text": null }, { "code": null, "e": 25287, "s": 25279, "text": "Output:" }, { "code": null, "e": 25354, "s": 25287, "text": "sun.reflect\nJava Runtime Environment\nOracle Corporation\n1.8.0_121\n" }, { "code": null, "e": 25906, "s": 25354, "text": "static Package getPackage(String name): Find a package by name in the callers ClassLoader instance. The callers ClassLoader instance is used to find the package instance corresponding to the named class. If the callers ClassLoader instance is null then the set of packages loaded by the system ClassLoader instance is searched to find the named package.Syntax: public static Package getPackage(String name)\nReturns: the package of the requested name. It may \nbe null if no package information is available from the archive or \ncodebase.\nException: NA\n" }, { "code": null, "e": 26105, "s": 25906, "text": "Syntax: public static Package getPackage(String name)\nReturns: the package of the requested name. It may \nbe null if no package information is available from the archive or \ncodebase.\nException: NA\n" }, { "code": null, "e": 27153, "s": 26105, "text": "static Package[] getPackages(): Get all the packages currently known for the caller’s ClassLoader instance. Those packages correspond to classes loaded via or accessible by name to that ClassLoader instance. If the caller’s ClassLoader instance is the bootstrap ClassLoader instance, which may be represented by null in some implementations, only packages corresponding to classes loaded by the bootstrap ClassLoader instance will be returned.Syntax: public static Package[] getPackages()\nReturns: a new array of packages known to the callers \nClassLoader instance. An zero length array is returned if none are known.\nException: NA\n// Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage(\"java.lang\"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }}Output:java.lang\nsun.reflect\n" }, { "code": null, "e": 27343, "s": 27153, "text": "Syntax: public static Package[] getPackages()\nReturns: a new array of packages known to the callers \nClassLoader instance. An zero length array is returned if none are known.\nException: NA\n" }, { "code": "// Java code illustrating getPackages() methodclass PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); Package pkg = Package.getPackage(\"java.lang\"); for(int i=0; i<1; i++) { System.out.println(pkg.getName()); System.out.println(pkgs[i].getName()); } }}", "e": 27730, "s": 27343, "text": null }, { "code": null, "e": 27738, "s": 27730, "text": "Output:" }, { "code": null, "e": 27761, "s": 27738, "text": "java.lang\nsun.reflect\n" }, { "code": null, "e": 27994, "s": 27761, "text": "String getSpecificationTitle(): Return the title of the specification that this package implements.Syntax: public String getSpecificationTitle()\nReturns: the specification title, null is returned \nif it is not known.\nexception: NA.\n" }, { "code": null, "e": 28128, "s": 27994, "text": "Syntax: public String getSpecificationTitle()\nReturns: the specification title, null is returned \nif it is not known.\nexception: NA.\n" }, { "code": null, "e": 28573, "s": 28128, "text": "String getSpecificationVersion(): Returns the version number of the specification that this package implements. This version string must be a sequence of nonnegative decimal integers separated by “.”‘s and may have leading zeros. When version strings are compared the most significant numbers are compared.Syntax: public String getSpecificationVersion().\nReturns: the specification version, null is returned \nif it is not known.\nException: NA.\n" }, { "code": null, "e": 28712, "s": 28573, "text": "Syntax: public String getSpecificationVersion().\nReturns: the specification version, null is returned \nif it is not known.\nException: NA.\n" }, { "code": null, "e": 29022, "s": 28712, "text": "String getSpecificationVendor(): Return the name of the organization, vendor, or company that owns and maintains the specification of the classes that implement this package.Syntax: public String getSpecificationVendor()\nReturns: the specification vendor, null is returned\n if it is not known.\nException: NA.\n" }, { "code": null, "e": 29158, "s": 29022, "text": "Syntax: public String getSpecificationVendor()\nReturns: the specification vendor, null is returned\n if it is not known.\nException: NA.\n" }, { "code": null, "e": 30148, "s": 29158, "text": "int hashCode(): Return the hash code computed from the package name.Syntax: Return the hash code computed from the package name.\nException: NA\nReturns: the hash code.\n// Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }}Output:685414683\nJava Platform API Specification\nOracle Corporation\n1.8\n" }, { "code": null, "e": 30248, "s": 30148, "text": "Syntax: Return the hash code computed from the package name.\nException: NA\nReturns: the hash code.\n" }, { "code": "// Java code illustrating hashCode(), getSpecificationTitle()// getSpecificationVendor() and getSpecificationVersion()class PackageDemo{ public static void main(String arg[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i<1; i++) { // name of the package System.out.println(pkgs[i].hashCode()); // checking title System.out.println(pkgs[i].getSpecificationTitle()); // checking the vendor System.out.println(pkgs[i].getSpecificationVendor()); // checking version System.out.println(pkgs[i].getSpecificationVersion()); } }}", "e": 30999, "s": 30248, "text": null }, { "code": null, "e": 31007, "s": 30999, "text": "Output:" }, { "code": null, "e": 31073, "s": 31007, "text": "685414683\nJava Platform API Specification\nOracle Corporation\n1.8\n" }, { "code": null, "e": 31568, "s": 31073, "text": "boolean isCompatibleWith(String desired): Compare this package’s specification version with a desired version. It returns true if this packages specification version number is greater than or equal to the desired version number.Syntax: public boolean isCompatibleWith(String desired).\nReturns: true if this package's version number is \ngreater than or equal to the desired version number\nException: \nNumberFormatException - if the desired or current version is not \nof the correct dotted form.\n" }, { "code": null, "e": 31835, "s": 31568, "text": "Syntax: public boolean isCompatibleWith(String desired).\nReturns: true if this package's version number is \ngreater than or equal to the desired version number\nException: \nNumberFormatException - if the desired or current version is not \nof the correct dotted form.\n" }, { "code": null, "e": 32000, "s": 31835, "text": "boolean isSealed(): Returns true if this package is sealed.Syntax: public boolean isSealed()\nReturns: true if the package is sealed, false otherwise.\nException: NA\n" }, { "code": null, "e": 32106, "s": 32000, "text": "Syntax: public boolean isSealed()\nReturns: true if the package is sealed, false otherwise.\nException: NA\n" }, { "code": null, "e": 32334, "s": 32106, "text": "boolean isSealed(URL url): Returns true if this package is sealed with respect to the specified code source url.Syntax: public boolean isSealed(URL url)\nReturns: true if this package is sealed with respect to url\nException: NA\n" }, { "code": null, "e": 32450, "s": 32334, "text": "Syntax: public boolean isSealed(URL url)\nReturns: true if this package is sealed with respect to url\nException: NA\n" }, { "code": null, "e": 33581, "s": 32450, "text": "String toString(): Returns the string representation of this Package. Its value is the string “package ” and the package name. If the package title is defined it is appended. If the package version is defined it is appended.Syntax: public String toString()\nReturns: the string representation of the package.\nException: NA\n// java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage(\"java.lang\"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith(\"1.0\")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL(\"https://www.youtube.com/\"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }}Output:true\nfalse\nfalse\npackage java.lang, Java Platform API Specification, version 1.8\n" }, { "code": null, "e": 33680, "s": 33581, "text": "Syntax: public String toString()\nReturns: the string representation of the package.\nException: NA\n" }, { "code": "// java code illustrating isCompatibleWith(), toString(),// isSealed methods import java.net.MalformedURLException;import java.net.URL; class PackageDemo{ public static void main(String arg[]) throws MalformedURLException { Package pkg = Package.getPackage(\"java.lang\"); // checking if pkg is compatible with 1.0 System.out.println(pkg.isCompatibleWith(\"1.0\")); // checking if packet is sealed System.out.println(pkg.isSealed()); URL url = new URL(\"https://www.youtube.com/\"); System.out.println(pkg.isSealed(url)); // string equivalent of package System.out.println(pkg.toString()); }}", "e": 34401, "s": 33680, "text": null }, { "code": null, "e": 34409, "s": 34401, "text": "Output:" }, { "code": null, "e": 34491, "s": 34409, "text": "true\nfalse\nfalse\npackage java.lang, Java Platform API Specification, version 1.8\n" }, { "code": null, "e": 34793, "s": 34491, "text": "This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34918, "s": 34793, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34936, "s": 34918, "text": "Java-lang package" }, { "code": null, "e": 34941, "s": 34936, "text": "Java" }, { "code": null, "e": 34946, "s": 34941, "text": "Java" }, { "code": null, "e": 35044, "s": 34946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35095, "s": 35044, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 35126, "s": 35095, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35156, "s": 35126, "text": "HashMap in Java with Examples" }, { "code": null, "e": 35174, "s": 35156, "text": "ArrayList in Java" }, { "code": null, "e": 35189, "s": 35174, "text": "Stream In Java" }, { "code": null, "e": 35209, "s": 35189, "text": "Collections in Java" }, { "code": null, "e": 35241, "s": 35209, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35265, "s": 35241, "text": "Singleton Class in Java" }, { "code": null, "e": 35285, "s": 35265, "text": "Stack Class in Java" } ]
How to get rows/index names in Pandas dataframe
02 Nov, 2021 While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations. Let’s discuss how to get row names in Pandas dataframe. First, let’s create a simple dataframe with nba.csv Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # calling head() method # storing in new variable data_top = data.head(10) # display data_top Now let’s try to get the row name from above dataset. Method #1: Simply iterate over indices Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # calling head() method # storing in new variable data_top = data.head() # iterating the columnsfor row in data_top.index: print(row, end = " ") Output: 0 1 2 3 4 5 6 7 8 9 Method #2: Using rows with dataframe object Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # calling head() method # storing in new variable data_top = data.head() # list(data_top) orlist(data_top.index) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #3: index.values method returns an array of index. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # calling head() method # storing in new variable data_top = data.head() list(data_top.index.values) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #4: Using tolist() method with values with given the list of index. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") # calling head() method # storing in new variable data_top = data.head() list(data_top.index.values.tolist()) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Method #5: Count number of rows in dataframe Since we have loaded only 10 top rows of dataframe using head() method, let’s verify total number of rows first. Python3 # iterate the indices and print each onefor row in data.index: print(row, end= " ") Output: Now, let’s print the total count of index. Python3 # Import pandas package import pandas as pd # making data frame data = pd.read_csv("nba.csv") row_count = 0 # iterating over indicesfor col in data.index: row_count += 1 # print the row countprint(row_count) Output: 458 prachisoda1234 pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2021" }, { "code": null, "e": 187, "s": 28, "text": "While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations." }, { "code": null, "e": 243, "s": 187, "text": "Let’s discuss how to get row names in Pandas dataframe." }, { "code": null, "e": 295, "s": 243, "text": "First, let’s create a simple dataframe with nba.csv" }, { "code": null, "e": 303, "s": 295, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # calling head() method # storing in new variable data_top = data.head(10) # display data_top ", "e": 556, "s": 303, "text": null }, { "code": null, "e": 610, "s": 556, "text": "Now let’s try to get the row name from above dataset." }, { "code": null, "e": 649, "s": 610, "text": "Method #1: Simply iterate over indices" }, { "code": null, "e": 657, "s": 649, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variable data_top = data.head() # iterating the columnsfor row in data_top.index: print(row, end = \" \")", "e": 910, "s": 657, "text": null }, { "code": null, "e": 918, "s": 910, "text": "Output:" }, { "code": null, "e": 939, "s": 918, "text": "0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 984, "s": 939, "text": " Method #2: Using rows with dataframe object" }, { "code": null, "e": 992, "s": 984, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variable data_top = data.head() # list(data_top) orlist(data_top.index)", "e": 1210, "s": 992, "text": null }, { "code": null, "e": 1218, "s": 1210, "text": "Output:" }, { "code": null, "e": 1249, "s": 1218, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 1308, "s": 1249, "text": " Method #3: index.values method returns an array of index." }, { "code": null, "e": 1316, "s": 1308, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variable data_top = data.head() list(data_top.index.values)", "e": 1522, "s": 1316, "text": null }, { "code": null, "e": 1530, "s": 1522, "text": "Output:" }, { "code": null, "e": 1561, "s": 1530, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 1637, "s": 1561, "text": " Method #4: Using tolist() method with values with given the list of index." }, { "code": null, "e": 1645, "s": 1637, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") # calling head() method # storing in new variable data_top = data.head() list(data_top.index.values.tolist())", "e": 1860, "s": 1645, "text": null }, { "code": null, "e": 1868, "s": 1860, "text": "Output:" }, { "code": null, "e": 1899, "s": 1868, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 1945, "s": 1899, "text": " Method #5: Count number of rows in dataframe" }, { "code": null, "e": 2058, "s": 1945, "text": "Since we have loaded only 10 top rows of dataframe using head() method, let’s verify total number of rows first." }, { "code": null, "e": 2066, "s": 2058, "text": "Python3" }, { "code": "# iterate the indices and print each onefor row in data.index: print(row, end= \" \")", "e": 2153, "s": 2066, "text": null }, { "code": null, "e": 2161, "s": 2153, "text": "Output:" }, { "code": null, "e": 2204, "s": 2161, "text": "Now, let’s print the total count of index." }, { "code": null, "e": 2212, "s": 2204, "text": "Python3" }, { "code": "# Import pandas package import pandas as pd # making data frame data = pd.read_csv(\"nba.csv\") row_count = 0 # iterating over indicesfor col in data.index: row_count += 1 # print the row countprint(row_count)", "e": 2431, "s": 2212, "text": null }, { "code": null, "e": 2439, "s": 2431, "text": "Output:" }, { "code": null, "e": 2443, "s": 2439, "text": "458" }, { "code": null, "e": 2458, "s": 2443, "text": "prachisoda1234" }, { "code": null, "e": 2483, "s": 2458, "text": "pandas-dataframe-program" }, { "code": null, "e": 2507, "s": 2483, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2521, "s": 2507, "text": "Python-pandas" }, { "code": null, "e": 2528, "s": 2521, "text": "Python" }, { "code": null, "e": 2626, "s": 2528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2658, "s": 2626, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2687, "s": 2658, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2714, "s": 2687, "text": "Python Classes and Objects" }, { "code": null, "e": 2735, "s": 2714, "text": "Python OOPs Concepts" }, { "code": null, "e": 2758, "s": 2735, "text": "Introduction To PYTHON" }, { "code": null, "e": 2814, "s": 2758, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2845, "s": 2814, "text": "Python | os.path.join() method" }, { "code": null, "e": 2882, "s": 2845, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 2924, "s": 2882, "text": "Check if element exists in list in Python" } ]
numpy.median() in Python
28 Nov, 2018 numpy.median(arr, axis = None) : Compute the median of the given data (array elements) along the specified axis. How to calculate median? Given data points. Arrange them in ascending order Median = middle term if total no. of terms are odd. Median = Average of the terms in the middle (if total no. of terms are even) Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the median. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing median. Results : Median of the array (a scalar value if axis is none) or array with median values along specified axis. Code #1: # Python Program illustrating # numpy.median() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print("arr : ", arr) print("median of arr : ", np.median(arr)) Output : arr : [20, 2, 7, 1, 34] median of arr : 7.0 Code #2: # Python Program illustrating # numpy.median() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] # median of the flattened array print("\nmedian of arr, axis = None : ", np.median(arr)) # median along the axis = 0 print("\nmedian of arr, axis = 0 : ", np.median(arr, axis = 0)) # median along the axis = 1 print("\nmedian of arr, axis = 1 : ", np.median(arr, axis = 1)) out_arr = np.arange(3)print("\nout_arr : ", out_arr) print("median of arr, axis = 1 : ", np.median(arr, axis = 1, out = out_arr)) Output : median of arr, axis = None : 15.0 median of arr, axis = 0 : [15. 6. 27. 8. 19.] median of arr, axis = 1 : [17. 15. 4.] out_arr : [0 1 2] median of arr, axis = 1 : [17 15 4] Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 141, "s": 28, "text": "numpy.median(arr, axis = None) : Compute the median of the given data (array elements) along the specified axis." }, { "code": null, "e": 166, "s": 141, "text": "How to calculate median?" }, { "code": null, "e": 185, "s": 166, "text": "Given data points." }, { "code": null, "e": 217, "s": 185, "text": "Arrange them in ascending order" }, { "code": null, "e": 269, "s": 217, "text": "Median = middle term if total no. of terms are odd." }, { "code": null, "e": 346, "s": 269, "text": "Median = Average of the terms in the middle (if total no. of terms are even)" }, { "code": null, "e": 819, "s": 346, "text": "Parameters :arr : [array_like]input array.axis : [int or tuples of int]axis along which we want to calculate the median. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional]Type we desire while computing median." }, { "code": null, "e": 932, "s": 819, "text": "Results : Median of the array (a scalar value if axis is none) or array with median values along specified axis." }, { "code": null, "e": 941, "s": 932, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.median() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print(\"arr : \", arr) print(\"median of arr : \", np.median(arr)) ", "e": 1123, "s": 941, "text": null }, { "code": null, "e": 1132, "s": 1123, "text": "Output :" }, { "code": null, "e": 1179, "s": 1132, "text": "arr : [20, 2, 7, 1, 34]\nmedian of arr : 7.0\n" }, { "code": null, "e": 1189, "s": 1179, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.median() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] # median of the flattened array print(\"\\nmedian of arr, axis = None : \", np.median(arr)) # median along the axis = 0 print(\"\\nmedian of arr, axis = 0 : \", np.median(arr, axis = 0)) # median along the axis = 1 print(\"\\nmedian of arr, axis = 1 : \", np.median(arr, axis = 1)) out_arr = np.arange(3)print(\"\\nout_arr : \", out_arr) print(\"median of arr, axis = 1 : \", np.median(arr, axis = 1, out = out_arr))", "e": 1783, "s": 1189, "text": null }, { "code": null, "e": 1792, "s": 1783, "text": "Output :" }, { "code": null, "e": 1978, "s": 1792, "text": "median of arr, axis = None : 15.0\n\nmedian of arr, axis = 0 : [15. 6. 27. 8. 19.]\n\nmedian of arr, axis = 1 : [17. 15. 4.]\n\nout_arr : [0 1 2]\nmedian of arr, axis = 1 : [17 15 4]\n" }, { "code": null, "e": 2012, "s": 1978, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 2025, "s": 2012, "text": "Python-numpy" }, { "code": null, "e": 2032, "s": 2025, "text": "Python" }, { "code": null, "e": 2130, "s": 2032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2148, "s": 2130, "text": "Python Dictionary" }, { "code": null, "e": 2190, "s": 2148, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2212, "s": 2190, "text": "Enumerate() in Python" }, { "code": null, "e": 2247, "s": 2212, "text": "Read a file line by line in Python" }, { "code": null, "e": 2273, "s": 2247, "text": "Python String | replace()" }, { "code": null, "e": 2305, "s": 2273, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2334, "s": 2305, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2361, "s": 2334, "text": "Python Classes and Objects" }, { "code": null, "e": 2391, "s": 2361, "text": "Iterate over a list in Python" } ]
Python MySQL - Select Data
You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set. Following is the syntax of the SELECT query − SELECT column1, column2, columnN FROM table_name; Assume we have created a table in MySQL with name cricketers_data as − CREATE TABLE cricketers_data( First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); And if we have inserted 5 records in to it using INSERT statements as − insert into cricketers_data values( 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into cricketers_data values( 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into cricketers_data values( 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into cricketers_data values( 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into cricketers_data values( 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); Following query retrieves the FIRST_NAME and Country values from the table. mysql> select FIRST_NAME, Country from cricketers_data; +------------+-------------+ | FIRST_NAME | Country | +------------+-------------+ | Shikhar | India | | Jonathan | SouthAfrica | | Kumara | Srilanka | | Virat | India | | Rohit | India | +------------+-------------+ 5 rows in set (0.00 sec) You can also retrieve all the values of each record using * instated of the name of the columns as − mysql> SELECT * from cricketers_data; +------------+------------+---------------+----------------+-------------+ | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country | +------------+------------+---------------+----------------+-------------+ | Shikhar | Dhawan | 1981-12-05 | Delhi | India | | Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica | | Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka | | Virat | Kohli | 1988-11-05 | Delhi | India | | Rohit | Sharma | 1987-04-30 | Nagpur | India | +------------+------------+---------------+----------------+-------------+ 5 rows in set (0.00 sec) READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python. The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones). The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchone() method fetches the next row in the result of a query and returns it as a tuple. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row. Note − A result set is an object that is returned when a cursor object is used to query a table. rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method. Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchone(); print(result) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Closing the connection conn.close() ('Krishna', 'Sharma', 19, 'M', 2000.0) [('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)] Following example retrieves first two rows of the EMPLOYEE table using the fetchmany() method. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row sql = '''SELECT * from EMPLOYEE''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchmany(size =2); print(result) #Closing the connection conn.close() [('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]
[ { "code": null, "e": 3522, "s": 3339, "text": "You can retrieve/fetch data from a table in MySQL using the SELECT query. This query/statement returns contents of the specified table in tabular form and it is called as result-set." }, { "code": null, "e": 3568, "s": 3522, "text": "Following is the syntax of the SELECT query −" }, { "code": null, "e": 3619, "s": 3568, "text": "SELECT column1, column2, columnN FROM table_name;\n" }, { "code": null, "e": 3690, "s": 3619, "text": "Assume we have created a table in MySQL with name cricketers_data as −" }, { "code": null, "e": 3858, "s": 3690, "text": "CREATE TABLE cricketers_data(\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\n" }, { "code": null, "e": 3930, "s": 3858, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 4437, "s": 3930, "text": "insert into cricketers_data values(\n 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into cricketers_data values(\n 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into cricketers_data values(\n 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into cricketers_data values(\n 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into cricketers_data values(\n 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');" }, { "code": null, "e": 4513, "s": 4437, "text": "Following query retrieves the FIRST_NAME and Country values from the table." }, { "code": null, "e": 4856, "s": 4513, "text": "mysql> select FIRST_NAME, Country from cricketers_data;\n+------------+-------------+\n| FIRST_NAME | Country |\n+------------+-------------+\n| Shikhar | India |\n| Jonathan | SouthAfrica |\n| Kumara | Srilanka |\n| Virat | India |\n| Rohit | India |\n+------------+-------------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 4957, "s": 4856, "text": "You can also retrieve all the values of each record using * instated of the name of the columns as −" }, { "code": null, "e": 5696, "s": 4957, "text": "mysql> SELECT * from cricketers_data;\n+------------+------------+---------------+----------------+-------------+\n| First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | Country |\n+------------+------------+---------------+----------------+-------------+\n| Shikhar | Dhawan | 1981-12-05 | Delhi | India |\n| Jonathan | Trott | 1981-04-22 | CapeTown | SouthAfrica |\n| Kumara | Sangakkara | 1977-10-27 | Matale | Srilanka |\n| Virat | Kohli | 1988-11-05 | Delhi | India |\n| Rohit | Sharma | 1987-04-30 | Nagpur | India |\n+------------+------------+---------------+----------------+-------------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 5880, "s": 5696, "text": "READ Operation on any database means to fetch some useful information from the database. You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python." }, { "code": null, "e": 5986, "s": 5880, "text": "The cursor.MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where," }, { "code": null, "e": 6174, "s": 5986, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 6362, "s": 6174, "text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows it returns the remaining ones)." }, { "code": null, "e": 6457, "s": 6362, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 6552, "s": 6457, "text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple." }, { "code": null, "e": 6698, "s": 6552, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 6844, "s": 6698, "text": "The fetchmany() method is similar to the fetchone() but, it retrieves the next set of rows in the result set of a query, instead of a single row." }, { "code": null, "e": 6941, "s": 6844, "text": "Note − A result set is an object that is returned when a cursor object is used to query a table." }, { "code": null, "e": 7056, "s": 6941, "text": "rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method." }, { "code": null, "e": 7310, "s": 7056, "text": "Following example fetches all the rows of the EMPLOYEE table using the SELECT query and from the obtained result set initially, we are retrieving the first row using the fetchone() method and then fetching the remaining rows using the fetchall() method." }, { "code": null, "e": 7834, "s": 7310, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchone();\nprint(result)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 7955, "s": 7834, "text": "('Krishna', 'Sharma', 19, 'M', 2000.0)\n[('Raj', 'Kandukuri', 20, 'M', 7000.0), ('Ramya', 'Ramapriya', 25, 'M', 5000.0)]\n" }, { "code": null, "e": 8050, "s": 7955, "text": "Following example retrieves first two rows of the EMPLOYEE table using the fetchmany() method." }, { "code": null, "e": 8506, "s": 8050, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMPLOYEE'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchmany(size =2);\nprint(result)\n\n#Closing the connection\nconn.close()" } ]
Operators in Scala
31 Aug, 2021 An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: Arithmetic Operators These are used to perform arithmetic/mathematical operations on operands. Addition(+) operator adds two operands. For example, x+y. Subtraction(-) operator subtracts two operands. For example, x-y. Multiplication(*) operator multiplies two operands. For example, x*y. Division(/) operator divides the first operand by the second. For example, x/y. Modulus(%) operator returns the remainder when the first operand is divided by the second. For example, x%y. Exponent(**) operator returns exponential(power) of the operands. For example, x**y. Example: Scala // Scala program to demonstrate// the Arithmetic Operators object Arithop{ def main(args: Array[String]){ // variables var a = 50; var b = 30; // Addition println("Addition of a + b = " + (a + b)); // Subtraction println("Subtraction of a - b = " + (a - b)); // Multiplication println("Multiplication of a * b = " + (a * b)); // Division println("Division of a / b = " + (a / b)); // Modulus println("Modulus of a % b = " + (a % b)); }} Output: Addition of a + b = 80 Subtraction of a - b = 20 Multiplication of a * b = 1500 Division of a / b = 1 Modulus of a % b = 20 Relational Operators Relational operators or Comparison operators are used for comparison of two values. Let’s see them one by one: Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true. Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false. Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true. Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false. Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true. Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true. Example: Scala // Scala program to demonstrate// the Relational Operatorsobject Relop{ def main(args: Array[String]){ // variables var a = 50; var b = 30; // Equal to operator println("Equality of a == b is : " + (a == b)); // Not equal to operator println("Not Equals of a != b is : " + (a != b)); // Greater than operator println("Greater than of a > b is : " + (a > b)); // Lesser than operator println("Lesser than of a < b is : " + (a < b)); // Greater than equal to operator println("Greater than or Equal to of a >= b is : " + (a >= b)); // Lesser than equal to operator println("Lesser than or Equal to of a <= b is : " + (a <= b)); }} Output: Equality of a == b is : false Not Equals of a != b is : true Greater than of a > b is : true Lesser than of a = b is : true Lesser than or Equal to of a <= b is : false Logical Operators They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below: Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero). Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true. Logical NOT(!) operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false. Example: Scala // Scala program to demonstrate// the Logical Operatorsobject Logop{ def main(args: Array[String]){ // variables var a = false var b = true // logical NOT operator println("Logical Not of !(a && b) = " + !(a && b)); // logical OR operator println("Logical Or of a || b = " + (a || b)); // logical AND operator println("Logical And of a && b = " + (a && b)); }} Output: Logical Not of !(a && b) = true Logical Or of a || b = true Logical And of a && b = false Assignment Operators Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below: Simple Assignment (=) operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left. Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left. Multiply AND Assignment (*=) operator is used for multiplying the left operand with right operand and then assigning it to the variable on the left. Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left. Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to the variable on the left. Exponent AND Assignment (**=) operator is used for raising power of the left operand to the right operand and assigning it to the variable on the left. Left shift AND Assignment(<<=)operator is used to perform binary left shift of the left operand with the right operand and assigning it to the variable on the left. Right shift AND Assignment(>>=)operator is used to perform binary right shift of the left operand with the right operand and assigning it to the variable on the left. Bitwise AND Assignment(&=)operator is used to perform Bitwise And of the left operand with the right operand and assigning it to the variable on the left. Bitwise exclusive OR and Assignment(^=)operator is used to perform Bitwise exclusive OR of the left operand with the right operand and assigning it to the variable on the left. Bitwise inclusive OR and Assignment(|=)operator is used to perform Bitwise inclusive OR of the left operand with the right operand and assigning it to the variable on the left. Example: Scala // Scala program to demonstrate// the Assignments Operatorsobject Assignop{ def main(args: Array[String]){ // variables var a = 50; var b = 40; var c = 0; // simple addition c = a + b; println("simple addition: c= a + b = " + c); // Add AND assignment c += a; println("Add and assignment of c += a = " + c); // Subtract AND assignment c -= a; println("Subtract and assignment of c -= a = " + c); // Multiply AND assignment c *= a; println("Multiplication and assignment of c *= a = " + c); // Divide AND assignment c /= a; println("Division and assignment of c /= a = " + c); // Modulus AND assignment c %= a; println("Modulus and assignment of c %= a = " + c); // Left shift AND assignment c <<= 3; println("Left shift and assignment of c <<= 3 = " + c); // Right shift AND assignment c >>= 3; println("Right shift and assignment of c >>= 3 = " + c); // Bitwise AND assignment c &= a; println("Bitwise And assignment of c &= 3 = " + c); // Bitwise exclusive OR and assignment c ^= a; println("Bitwise Xor and assignment of c ^= a = " + c); // Bitwise inclusive OR and assignment c |= a; println("Bitwise Or and assignment of c |= a = " + c);}} Output: simple addition: c= a + b = 90 Add and assignment of c += a = 140 Subtract and assignment of c -= a = 90 Multiplication and assignment of c *= a = 4500 Division and assignment of c /= a = 90 Modulus and assignment of c %= a = 40 Left shift and assignment of c <<= 3 = 320 Right shift and assignment of c >>= 3 = 40 Bitwise And assignment of c &= 3 = 32 Bitwise Xor and assignment of c ^= a = 18 Bitwise Or and assignment of c |= a = 50 Bitwise Operators In Scala, there are 7 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators : Bitwise AND (&): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. Bitwise OR (|): Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1. Bitwise XOR (^): Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. Bitwise left Shift (<<): Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. Bitwise right Shift (>>): Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. Bitwise ones Complement (~): This operator takes a single number and used to perform the complement operation of 8-bit. Bitwise shift right zero fill(>>>): In shift right zero fill operator, left operand is shifted right by the number of bits specified by the right operand, and the shifted values are filled up with zeros. Example: Scala // Scala program to demonstrate// the Bitwise Operatorsobject Bitop{def main(args: Array[String]){ // variables var a = 20; var b = 18; var c = 0; // Bitwise AND operator c = a & b; println("Bitwise And of a & b = " + c); // Bitwise OR operator c = a | b; println("Bitwise Or of a | b = " + c); // Bitwise XOR operator c = a ^ b; println("Bitwise Xor of a ^ b = " + c); // Bitwise once complement operator c = ~a; println("Bitwise Ones Complement of ~a = " + c); // Bitwise left shift operator c = a << 3; println("Bitwise Left Shift of a << 3 = " + c); // Bitwise right shift operator c = a >> 3; println("Bitwise Right Shift of a >> 3 = " + c); // Bitwise shift right zero fill operator c = a >>> 4; println("Bitwise Shift Right a >>> 4 = " + c);}} Output: Bitwise And of a & b = 16 Bitwise Or of a | b = 22 Bitwise Xor of a ^ b = 6 Bitwise Ones Complement of ~a = -21 Bitwise Left Shift of a << 3 = 160 Bitwise Right Shift of a >> 3 = 2 Bitwise Shift Right a >>> 4 = 1 surinderdawra388 simmytarika5 clintra Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 346, "s": 54, "text": "An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: " }, { "code": null, "e": 367, "s": 346, "text": "Arithmetic Operators" }, { "code": null, "e": 443, "s": 367, "text": "These are used to perform arithmetic/mathematical operations on operands. " }, { "code": null, "e": 501, "s": 443, "text": "Addition(+) operator adds two operands. For example, x+y." }, { "code": null, "e": 567, "s": 501, "text": "Subtraction(-) operator subtracts two operands. For example, x-y." }, { "code": null, "e": 637, "s": 567, "text": "Multiplication(*) operator multiplies two operands. For example, x*y." }, { "code": null, "e": 717, "s": 637, "text": "Division(/) operator divides the first operand by the second. For example, x/y." }, { "code": null, "e": 826, "s": 717, "text": "Modulus(%) operator returns the remainder when the first operand is divided by the second. For example, x%y." }, { "code": null, "e": 911, "s": 826, "text": "Exponent(**) operator returns exponential(power) of the operands. For example, x**y." }, { "code": null, "e": 922, "s": 911, "text": "Example: " }, { "code": null, "e": 928, "s": 922, "text": "Scala" }, { "code": "// Scala program to demonstrate// the Arithmetic Operators object Arithop{ def main(args: Array[String]){ // variables var a = 50; var b = 30; // Addition println(\"Addition of a + b = \" + (a + b)); // Subtraction println(\"Subtraction of a - b = \" + (a - b)); // Multiplication println(\"Multiplication of a * b = \" + (a * b)); // Division println(\"Division of a / b = \" + (a / b)); // Modulus println(\"Modulus of a % b = \" + (a % b)); }}", "e": 1429, "s": 928, "text": null }, { "code": null, "e": 1438, "s": 1429, "text": "Output: " }, { "code": null, "e": 1562, "s": 1438, "text": "Addition of a + b = 80\nSubtraction of a - b = 20\nMultiplication of a * b = 1500\nDivision of a / b = 1\nModulus of a % b = 20" }, { "code": null, "e": 1583, "s": 1562, "text": "Relational Operators" }, { "code": null, "e": 1695, "s": 1583, "text": "Relational operators or Comparison operators are used for comparison of two values. Let’s see them one by one: " }, { "code": null, "e": 1861, "s": 1695, "text": "Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true." }, { "code": null, "e": 2090, "s": 1861, "text": "Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false." }, { "code": null, "e": 2271, "s": 2090, "text": "Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true." }, { "code": null, "e": 2449, "s": 2271, "text": "Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false." }, { "code": null, "e": 2653, "s": 2449, "text": "Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true." }, { "code": null, "e": 2858, "s": 2653, "text": "Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true." }, { "code": null, "e": 2867, "s": 2858, "text": "Example:" }, { "code": null, "e": 2873, "s": 2867, "text": "Scala" }, { "code": "// Scala program to demonstrate// the Relational Operatorsobject Relop{ def main(args: Array[String]){ // variables var a = 50; var b = 30; // Equal to operator println(\"Equality of a == b is : \" + (a == b)); // Not equal to operator println(\"Not Equals of a != b is : \" + (a != b)); // Greater than operator println(\"Greater than of a > b is : \" + (a > b)); // Lesser than operator println(\"Lesser than of a < b is : \" + (a < b)); // Greater than equal to operator println(\"Greater than or Equal to of a >= b is : \" + (a >= b)); // Lesser than equal to operator println(\"Lesser than or Equal to of a <= b is : \" + (a <= b)); }}", "e": 3573, "s": 2873, "text": null }, { "code": null, "e": 3582, "s": 3573, "text": "Output: " }, { "code": null, "e": 3754, "s": 3582, "text": "Equality of a == b is : false\nNot Equals of a != b is : true\nGreater than of a > b is : true\nLesser than of a = b is : true\nLesser than or Equal to of a <= b is : false" }, { "code": null, "e": 3772, "s": 3754, "text": "Logical Operators" }, { "code": null, "e": 3934, "s": 3772, "text": "They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:" }, { "code": null, "e": 4179, "s": 3934, "text": "Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero)." }, { "code": null, "e": 4486, "s": 4179, "text": "Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true." }, { "code": null, "e": 4678, "s": 4486, "text": "Logical NOT(!) operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false." }, { "code": null, "e": 4687, "s": 4678, "text": "Example:" }, { "code": null, "e": 4693, "s": 4687, "text": "Scala" }, { "code": "// Scala program to demonstrate// the Logical Operatorsobject Logop{ def main(args: Array[String]){ // variables var a = false var b = true // logical NOT operator println(\"Logical Not of !(a && b) = \" + !(a && b)); // logical OR operator println(\"Logical Or of a || b = \" + (a || b)); // logical AND operator println(\"Logical And of a && b = \" + (a && b)); }}", "e": 5101, "s": 4693, "text": null }, { "code": null, "e": 5110, "s": 5101, "text": "Output: " }, { "code": null, "e": 5200, "s": 5110, "text": "Logical Not of !(a && b) = true\nLogical Or of a || b = true\nLogical And of a && b = false" }, { "code": null, "e": 5221, "s": 5200, "text": "Assignment Operators" }, { "code": null, "e": 5605, "s": 5221, "text": "Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below: " }, { "code": null, "e": 5757, "s": 5605, "text": "Simple Assignment (=) operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left." }, { "code": null, "e": 5888, "s": 5757, "text": "Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left." }, { "code": null, "e": 6029, "s": 5888, "text": "Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left." }, { "code": null, "e": 6178, "s": 6029, "text": "Multiply AND Assignment (*=) operator is used for multiplying the left operand with right operand and then assigning it to the variable on the left." }, { "code": null, "e": 6314, "s": 6178, "text": "Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left." }, { "code": null, "e": 6466, "s": 6314, "text": "Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to the variable on the left." }, { "code": null, "e": 6618, "s": 6466, "text": "Exponent AND Assignment (**=) operator is used for raising power of the left operand to the right operand and assigning it to the variable on the left." }, { "code": null, "e": 6783, "s": 6618, "text": "Left shift AND Assignment(<<=)operator is used to perform binary left shift of the left operand with the right operand and assigning it to the variable on the left." }, { "code": null, "e": 6950, "s": 6783, "text": "Right shift AND Assignment(>>=)operator is used to perform binary right shift of the left operand with the right operand and assigning it to the variable on the left." }, { "code": null, "e": 7105, "s": 6950, "text": "Bitwise AND Assignment(&=)operator is used to perform Bitwise And of the left operand with the right operand and assigning it to the variable on the left." }, { "code": null, "e": 7282, "s": 7105, "text": "Bitwise exclusive OR and Assignment(^=)operator is used to perform Bitwise exclusive OR of the left operand with the right operand and assigning it to the variable on the left." }, { "code": null, "e": 7459, "s": 7282, "text": "Bitwise inclusive OR and Assignment(|=)operator is used to perform Bitwise inclusive OR of the left operand with the right operand and assigning it to the variable on the left." }, { "code": null, "e": 7469, "s": 7459, "text": "Example: " }, { "code": null, "e": 7475, "s": 7469, "text": "Scala" }, { "code": "// Scala program to demonstrate// the Assignments Operatorsobject Assignop{ def main(args: Array[String]){ // variables var a = 50; var b = 40; var c = 0; // simple addition c = a + b; println(\"simple addition: c= a + b = \" + c); // Add AND assignment c += a; println(\"Add and assignment of c += a = \" + c); // Subtract AND assignment c -= a; println(\"Subtract and assignment of c -= a = \" + c); // Multiply AND assignment c *= a; println(\"Multiplication and assignment of c *= a = \" + c); // Divide AND assignment c /= a; println(\"Division and assignment of c /= a = \" + c); // Modulus AND assignment c %= a; println(\"Modulus and assignment of c %= a = \" + c); // Left shift AND assignment c <<= 3; println(\"Left shift and assignment of c <<= 3 = \" + c); // Right shift AND assignment c >>= 3; println(\"Right shift and assignment of c >>= 3 = \" + c); // Bitwise AND assignment c &= a; println(\"Bitwise And assignment of c &= 3 = \" + c); // Bitwise exclusive OR and assignment c ^= a; println(\"Bitwise Xor and assignment of c ^= a = \" + c); // Bitwise inclusive OR and assignment c |= a; println(\"Bitwise Or and assignment of c |= a = \" + c);}}", "e": 8791, "s": 7475, "text": null }, { "code": null, "e": 8800, "s": 8791, "text": "Output: " }, { "code": null, "e": 9236, "s": 8800, "text": "simple addition: c= a + b = 90\nAdd and assignment of c += a = 140\nSubtract and assignment of c -= a = 90\nMultiplication and assignment of c *= a = 4500\nDivision and assignment of c /= a = 90\nModulus and assignment of c %= a = 40\nLeft shift and assignment of c <<= 3 = 320\nRight shift and assignment of c >>= 3 = 40\nBitwise And assignment of c &= 3 = 32\nBitwise Xor and assignment of c ^= a = 18\nBitwise Or and assignment of c |= a = 50" }, { "code": null, "e": 9254, "s": 9236, "text": "Bitwise Operators" }, { "code": null, "e": 9399, "s": 9254, "text": "In Scala, there are 7 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators : " }, { "code": null, "e": 9536, "s": 9399, "text": "Bitwise AND (&): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1." }, { "code": null, "e": 9671, "s": 9536, "text": "Bitwise OR (|): Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1." }, { "code": null, "e": 9814, "s": 9671, "text": "Bitwise XOR (^): Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different." }, { "code": null, "e": 9959, "s": 9814, "text": "Bitwise left Shift (<<): Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift." }, { "code": null, "e": 10106, "s": 9959, "text": "Bitwise right Shift (>>): Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift." }, { "code": null, "e": 10226, "s": 10106, "text": "Bitwise ones Complement (~): This operator takes a single number and used to perform the complement operation of 8-bit." }, { "code": null, "e": 10430, "s": 10226, "text": "Bitwise shift right zero fill(>>>): In shift right zero fill operator, left operand is shifted right by the number of bits specified by the right operand, and the shifted values are filled up with zeros." }, { "code": null, "e": 10440, "s": 10430, "text": "Example: " }, { "code": null, "e": 10446, "s": 10440, "text": "Scala" }, { "code": "// Scala program to demonstrate// the Bitwise Operatorsobject Bitop{def main(args: Array[String]){ // variables var a = 20; var b = 18; var c = 0; // Bitwise AND operator c = a & b; println(\"Bitwise And of a & b = \" + c); // Bitwise OR operator c = a | b; println(\"Bitwise Or of a | b = \" + c); // Bitwise XOR operator c = a ^ b; println(\"Bitwise Xor of a ^ b = \" + c); // Bitwise once complement operator c = ~a; println(\"Bitwise Ones Complement of ~a = \" + c); // Bitwise left shift operator c = a << 3; println(\"Bitwise Left Shift of a << 3 = \" + c); // Bitwise right shift operator c = a >> 3; println(\"Bitwise Right Shift of a >> 3 = \" + c); // Bitwise shift right zero fill operator c = a >>> 4; println(\"Bitwise Shift Right a >>> 4 = \" + c);}}", "e": 11307, "s": 10446, "text": null }, { "code": null, "e": 11316, "s": 11307, "text": "Output: " }, { "code": null, "e": 11529, "s": 11316, "text": "Bitwise And of a & b = 16\nBitwise Or of a | b = 22\nBitwise Xor of a ^ b = 6\nBitwise Ones Complement of ~a = -21\nBitwise Left Shift of a << 3 = 160\nBitwise Right Shift of a >> 3 = 2\nBitwise Shift Right a >>> 4 = 1" }, { "code": null, "e": 11546, "s": 11529, "text": "surinderdawra388" }, { "code": null, "e": 11559, "s": 11546, "text": "simmytarika5" }, { "code": null, "e": 11567, "s": 11559, "text": "clintra" }, { "code": null, "e": 11573, "s": 11567, "text": "Scala" }, { "code": null, "e": 11586, "s": 11573, "text": "Scala-Basics" }, { "code": null, "e": 11592, "s": 11586, "text": "Scala" } ]
Division Operators in Python
07 Jun, 2022 Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. There are two types of division operators: The quotient returns by this operator is always a float number, no matter if two numbers are integer. For example: >>>5/5 1.0 >>>10/2 5.0 >>>-10/2 -5.0 >>>20.0/2 10.0 The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example: >>>5//5 1 >>>3//2 1 >>>10//3 3 Consider the below statements in Python. Python3 # A Python program to demonstrate the use of# "//" for integersprint (5//2)print (-5//2) Output: 2 -3 The first output is fine, but the second one may be surprised if we are coming Java/C++ world. In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator ‘/’ returns always a float value. Note: The “//” operator is used to return the closest integer value which is less than or equal to a specified expression or value. So from the above code, 5//2 returns 2. You know that 5/2 is 2.5, and the closest integer which is less than or equal is 2[5//2].( it is inverse to the normal maths, in normal maths the value is 3). Example Python3 # A Python program to demonstrate use of# "/" for floating point numbersprint (5.0/2)print (-5.0/2) 2.5 -2.5 The real floor division operator is “//”. It returns the floor value for both integer and floating-point arguments. Python3 # A Python program to demonstrate use of# "//" for both integers and floating pointsprint (5//2)print (-5//2)print (5.0//2)print (-5.0//2) 2 -3 2.0 -3.0 See this for example. Python Programming Tutorial - Operators - Part 1 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial - Operators - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oiJUZbRIR7Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> f20180508 vicky2321984 sheetal18june Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Reverse a string in Java Arrays in C/C++ Interfaces in Java Inheritance in C++ Object Oriented Programming in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 253, "s": 52, "text": "Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. " }, { "code": null, "e": 297, "s": 253, "text": "There are two types of division operators: " }, { "code": null, "e": 412, "s": 297, "text": "The quotient returns by this operator is always a float number, no matter if two numbers are integer. For example:" }, { "code": null, "e": 464, "s": 412, "text": ">>>5/5\n1.0\n>>>10/2\n5.0\n>>>-10/2\n-5.0\n>>>20.0/2\n10.0" }, { "code": null, "e": 723, "s": 464, "text": "The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:" }, { "code": null, "e": 754, "s": 723, "text": ">>>5//5\n1\n>>>3//2\n1\n>>>10//3\n3" }, { "code": null, "e": 795, "s": 754, "text": "Consider the below statements in Python." }, { "code": null, "e": 803, "s": 795, "text": "Python3" }, { "code": "# A Python program to demonstrate the use of# \"//\" for integersprint (5//2)print (-5//2)", "e": 892, "s": 803, "text": null }, { "code": null, "e": 900, "s": 892, "text": "Output:" }, { "code": null, "e": 905, "s": 900, "text": "2\n-3" }, { "code": null, "e": 1153, "s": 905, "text": "The first output is fine, but the second one may be surprised if we are coming Java/C++ world. In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator ‘/’ returns always a float value." }, { "code": null, "e": 1484, "s": 1153, "text": "Note: The “//” operator is used to return the closest integer value which is less than or equal to a specified expression or value. So from the above code, 5//2 returns 2. You know that 5/2 is 2.5, and the closest integer which is less than or equal is 2[5//2].( it is inverse to the normal maths, in normal maths the value is 3)." }, { "code": null, "e": 1492, "s": 1484, "text": "Example" }, { "code": null, "e": 1500, "s": 1492, "text": "Python3" }, { "code": "# A Python program to demonstrate use of# \"/\" for floating point numbersprint (5.0/2)print (-5.0/2)", "e": 1600, "s": 1500, "text": null }, { "code": null, "e": 1610, "s": 1600, "text": "2.5\n-2.5\n" }, { "code": null, "e": 1726, "s": 1610, "text": "The real floor division operator is “//”. It returns the floor value for both integer and floating-point arguments." }, { "code": null, "e": 1734, "s": 1726, "text": "Python3" }, { "code": "# A Python program to demonstrate use of# \"//\" for both integers and floating pointsprint (5//2)print (-5//2)print (5.0//2)print (-5.0//2)", "e": 1873, "s": 1734, "text": null }, { "code": null, "e": 1888, "s": 1873, "text": "2\n-3\n2.0\n-3.0\n" }, { "code": null, "e": 1911, "s": 1888, "text": "See this for example. " }, { "code": null, "e": 2825, "s": 1911, "text": "Python Programming Tutorial - Operators - Part 1 | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial - Operators - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:38•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oiJUZbRIR7Y\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 2835, "s": 2825, "text": "f20180508" }, { "code": null, "e": 2848, "s": 2835, "text": "vicky2321984" }, { "code": null, "e": 2862, "s": 2848, "text": "sheetal18june" }, { "code": null, "e": 2869, "s": 2862, "text": "Python" }, { "code": null, "e": 2888, "s": 2869, "text": "School Programming" }, { "code": null, "e": 2986, "s": 2888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3014, "s": 2986, "text": "Read JSON file using Python" }, { "code": null, "e": 3064, "s": 3014, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3086, "s": 3064, "text": "Python map() function" }, { "code": null, "e": 3130, "s": 3086, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3172, "s": 3130, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3197, "s": 3172, "text": "Reverse a string in Java" }, { "code": null, "e": 3213, "s": 3197, "text": "Arrays in C/C++" }, { "code": null, "e": 3232, "s": 3213, "text": "Interfaces in Java" }, { "code": null, "e": 3251, "s": 3232, "text": "Inheritance in C++" } ]
Scanner nextLine() method in Java with Examples
12 Oct, 2018 The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present. Syntax: public String nextLine() Parameters: The function does not accepts any parameter. Return Value: This method returns the line that was skipped Exceptions: The function throws two exceptions as described below: NoSuchElementException: throws if no line was found IllegalStateException: throws if this scanner is closed Below programs illustrate the above function: Program 1: // Java program to illustrate the// nextLine() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Gfg \n Geeks \n GeeksForGeeks"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print the next line System.out.println(scanner.nextLine()); // print the next line again System.out.println(scanner.nextLine()); // print the next line again System.out.println(scanner.nextLine()); scanner.close(); }} Gfg Geeks GeeksForGeeks Program 2: To demonstrate NoSuchElementException // Java program to illustrate the// nextLine() method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = ""; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); System.out.println(scanner.nextLine()); scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Exception thrown: java.util.NoSuchElementException: No line found Program 3: To demonstrate IllegalStateException // Java program to illustrate the// nextLine() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); scanner.close(); // Prints the new line System.out.println(scanner.nextLine()); scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Exception thrown: java.lang.IllegalStateException: Scanner closed Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() Java - util package Java-Functions Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Oct, 2018" }, { "code": null, "e": 509, "s": 54, "text": "The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line separator, it may search all of the input searching for the line to skip if no line separators are present." }, { "code": null, "e": 517, "s": 509, "text": "Syntax:" }, { "code": null, "e": 542, "s": 517, "text": "public String nextLine()" }, { "code": null, "e": 599, "s": 542, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 659, "s": 599, "text": "Return Value: This method returns the line that was skipped" }, { "code": null, "e": 726, "s": 659, "text": "Exceptions: The function throws two exceptions as described below:" }, { "code": null, "e": 778, "s": 726, "text": "NoSuchElementException: throws if no line was found" }, { "code": null, "e": 834, "s": 778, "text": "IllegalStateException: throws if this scanner is closed" }, { "code": null, "e": 880, "s": 834, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 891, "s": 880, "text": "Program 1:" }, { "code": "// Java program to illustrate the// nextLine() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Gfg \\n Geeks \\n GeeksForGeeks\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print the next line System.out.println(scanner.nextLine()); // print the next line again System.out.println(scanner.nextLine()); // print the next line again System.out.println(scanner.nextLine()); scanner.close(); }}", "e": 1554, "s": 891, "text": null }, { "code": null, "e": 1583, "s": 1554, "text": "Gfg \n Geeks \n GeeksForGeeks\n" }, { "code": null, "e": 1632, "s": 1583, "text": "Program 2: To demonstrate NoSuchElementException" }, { "code": "// Java program to illustrate the// nextLine() method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); System.out.println(scanner.nextLine()); scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 2187, "s": 1632, "text": null }, { "code": null, "e": 2254, "s": 2187, "text": "Exception thrown: java.util.NoSuchElementException: No line found\n" }, { "code": null, "e": 2302, "s": 2254, "text": "Program 3: To demonstrate IllegalStateException" }, { "code": "// Java program to illustrate the// nextLine() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); scanner.close(); // Prints the new line System.out.println(scanner.nextLine()); scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 2944, "s": 2302, "text": null }, { "code": null, "e": 3011, "s": 2944, "text": "Exception thrown: java.lang.IllegalStateException: Scanner closed\n" }, { "code": null, "e": 3098, "s": 3011, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()" }, { "code": null, "e": 3118, "s": 3098, "text": "Java - util package" }, { "code": null, "e": 3133, "s": 3118, "text": "Java-Functions" }, { "code": null, "e": 3146, "s": 3133, "text": "Java-Library" }, { "code": null, "e": 3151, "s": 3146, "text": "Java" }, { "code": null, "e": 3156, "s": 3151, "text": "Java" }, { "code": null, "e": 3254, "s": 3156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3305, "s": 3254, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3336, "s": 3305, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3355, "s": 3336, "text": "Interfaces in Java" }, { "code": null, "e": 3385, "s": 3355, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3403, "s": 3385, "text": "ArrayList in Java" }, { "code": null, "e": 3418, "s": 3403, "text": "Stream In Java" }, { "code": null, "e": 3438, "s": 3418, "text": "Collections in Java" }, { "code": null, "e": 3470, "s": 3438, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3494, "s": 3470, "text": "Singleton Class in Java" } ]
Java Program for Third largest element in an array of distinct elements
03 Jan, 2022 Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20} Output: The third Largest element is 14 Explanation: Largest element is 20, second largest element is 16 and third largest element is 14 Input: arr[] = {19, -10, 20, 14, 2, 16, 10} Output: The third Largest element is 16 Explanation: Largest element is 20, second largest element is 19 and third largest element is 16 Naive Approach: The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e the maximum element excluding the maximum and second maximum. Algorithm: First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. First, iterate through the array and find maximum. Store this as first maximum along with its index. Now traverse the whole array finding the second max, excluding the maximum element. Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. Java // Java program to find third // Largest element in an array// of distinct elements class GFG{static void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { System.out.printf(" Invalid Input "); return; } // Find first // largest element int first = arr[0]; for (int i = 1; i < arr_size ; i++) if (arr[i] > first) first = arr[i]; // Find second // largest element int second = Integer.MIN_VALUE; for (int i = 0; i < arr_size ; i++) if (arr[i] > second && arr[i] < first) second = arr[i]; // Find third // largest element int third = Integer.MIN_VALUE; for (int i = 0; i < arr_size ; i++) if (arr[i] > third && arr[i] < second) third = arr[i]; System.out.printf("The third Largest " + "element is %d", third);} // Driver codepublic static void main(String []args){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = arr.length; thirdLargest(arr, n);}} // This code is contributed// by Smitha Output: The third Largest element is 13 Complexity Analysis: Time Complexity: O(n). As the array is iterated thrice and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space. Time Complexity: O(n). As the array is iterated thrice and is done in a constant time Space complexity: O(1). No extra space is needed as the indices can be stored in constant space. Efficient Approach: The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So the idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array. Algorithm: Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value). Move along the input array from start to the end. For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest. Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest. If the previous two conditions fail, but the element is larger than the third, then update the third. Print the value of third after traversing the array from start to end Java // Java program to find third Largest element in an arrayclass GFG { static void thirdLargest(int arr[], int arr_size) { /* There should be atleast three elements */ if (arr_size < 3) { System.out.printf(" Invalid Input "); return; } // Initialize first, second and third Largest element int first = arr[0], second = Integer.MIN_VALUE, third = Integer.MIN_VALUE; // Traverse array elements to find the third Largest for (int i = 1; i < arr_size; i++) { /* If current element is greater than first, then update first, second and third */ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second */ else if (arr[i] > second) { third = second; second = arr[i]; } /* If arr[i] is in between second and third */ else if (arr[i] > third) { third = arr[i]; } } System.out.printf("The third Largest element is %d", third); } /* Driver program to test above function */ public static void main(String []args) { int arr[] = {12, 13, 1, 10, 34, 16}; int n = arr.length; thirdLargest(arr, n); }}//This code is contributed by 29AjayKumar Output: The third Largest element is 13 Complexity Analysis:Time Complexity: O(n). As the array is iterated once and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space. Time Complexity: O(n). As the array is iterated once and is done in a constant time Space complexity: O(1). No extra space is needed as the indices can be stored in constant space. Please refer complete article on Third largest element in an array of distinct elements for more details! Amazon Arrays Java Java Programs Searching Amazon Arrays Searching Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2022" }, { "code": null, "e": 155, "s": 28, "text": "Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : " }, { "code": null, "e": 516, "s": 155, "text": "Input: arr[] = {1, 14, 2, 16, 10, 20}\nOutput: The third Largest element is 14\n\nExplanation: Largest element is 20, second largest element is 16 \nand third largest element is 14\n\nInput: arr[] = {19, -10, 20, 14, 2, 16, 10}\nOutput: The third Largest element is 16\n\nExplanation: Largest element is 20, second largest element is 19 \nand third largest element is 16" }, { "code": null, "e": 902, "s": 518, "text": "Naive Approach: The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e the maximum element excluding the maximum and second maximum. " }, { "code": null, "e": 1221, "s": 902, "text": "Algorithm: First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1529, "s": 1221, "text": "First, iterate through the array and find maximum.Store this as first maximum along with its index.Now traverse the whole array finding the second max, excluding the maximum element.Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1580, "s": 1529, "text": "First, iterate through the array and find maximum." }, { "code": null, "e": 1630, "s": 1580, "text": "Store this as first maximum along with its index." }, { "code": null, "e": 1714, "s": 1630, "text": "Now traverse the whole array finding the second max, excluding the maximum element." }, { "code": null, "e": 1840, "s": 1714, "text": "Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. " }, { "code": null, "e": 1845, "s": 1840, "text": "Java" }, { "code": "// Java program to find third // Largest element in an array// of distinct elements class GFG{static void thirdLargest(int arr[], int arr_size){ /* There should be atleast three elements */ if (arr_size < 3) { System.out.printf(\" Invalid Input \"); return; } // Find first // largest element int first = arr[0]; for (int i = 1; i < arr_size ; i++) if (arr[i] > first) first = arr[i]; // Find second // largest element int second = Integer.MIN_VALUE; for (int i = 0; i < arr_size ; i++) if (arr[i] > second && arr[i] < first) second = arr[i]; // Find third // largest element int third = Integer.MIN_VALUE; for (int i = 0; i < arr_size ; i++) if (arr[i] > third && arr[i] < second) third = arr[i]; System.out.printf(\"The third Largest \" + \"element is %d\", third);} // Driver codepublic static void main(String []args){ int arr[] = {12, 13, 1, 10, 34, 16}; int n = arr.length; thirdLargest(arr, n);}} // This code is contributed// by Smitha", "e": 3049, "s": 1845, "text": null }, { "code": null, "e": 3059, "s": 3049, "text": "Output: " }, { "code": null, "e": 3091, "s": 3059, "text": "The third Largest element is 13" }, { "code": null, "e": 3294, "s": 3091, "text": "Complexity Analysis: Time Complexity: O(n). As the array is iterated thrice and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 3380, "s": 3294, "text": "Time Complexity: O(n). As the array is iterated thrice and is done in a constant time" }, { "code": null, "e": 3477, "s": 3380, "text": "Space complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 3970, "s": 3477, "text": "Efficient Approach: The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So the idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array. " }, { "code": null, "e": 4835, "s": 3970, "text": "Algorithm: Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end " }, { "code": null, "e": 5689, "s": 4835, "text": "Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).Move along the input array from start to the end.For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.If the previous two conditions fail, but the element is larger than the third, then update the third.Print the value of third after traversing the array from start to end " }, { "code": null, "e": 5852, "s": 5689, "text": "Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value)." }, { "code": null, "e": 5902, "s": 5852, "text": "Move along the input array from start to the end." }, { "code": null, "e": 6242, "s": 5902, "text": "For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest." }, { "code": null, "e": 6375, "s": 6242, "text": "Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest." }, { "code": null, "e": 6477, "s": 6375, "text": "If the previous two conditions fail, but the element is larger than the third, then update the third." }, { "code": null, "e": 6548, "s": 6477, "text": "Print the value of third after traversing the array from start to end " }, { "code": null, "e": 6553, "s": 6548, "text": "Java" }, { "code": "// Java program to find third Largest element in an arrayclass GFG { static void thirdLargest(int arr[], int arr_size) { /* There should be atleast three elements */ if (arr_size < 3) { System.out.printf(\" Invalid Input \"); return; } // Initialize first, second and third Largest element int first = arr[0], second = Integer.MIN_VALUE, third = Integer.MIN_VALUE; // Traverse array elements to find the third Largest for (int i = 1; i < arr_size; i++) { /* If current element is greater than first, then update first, second and third */ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second */ else if (arr[i] > second) { third = second; second = arr[i]; } /* If arr[i] is in between second and third */ else if (arr[i] > third) { third = arr[i]; } } System.out.printf(\"The third Largest element is %d\", third); } /* Driver program to test above function */ public static void main(String []args) { int arr[] = {12, 13, 1, 10, 34, 16}; int n = arr.length; thirdLargest(arr, n); }}//This code is contributed by 29AjayKumar", "e": 7969, "s": 6553, "text": null }, { "code": null, "e": 7979, "s": 7969, "text": "Output: " }, { "code": null, "e": 8011, "s": 7979, "text": "The third Largest element is 13" }, { "code": null, "e": 8211, "s": 8011, "text": "Complexity Analysis:Time Complexity: O(n). As the array is iterated once and is done in a constant timeSpace complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 8295, "s": 8211, "text": "Time Complexity: O(n). As the array is iterated once and is done in a constant time" }, { "code": null, "e": 8392, "s": 8295, "text": "Space complexity: O(1). No extra space is needed as the indices can be stored in constant space." }, { "code": null, "e": 8498, "s": 8392, "text": "Please refer complete article on Third largest element in an array of distinct elements for more details!" }, { "code": null, "e": 8505, "s": 8498, "text": "Amazon" }, { "code": null, "e": 8512, "s": 8505, "text": "Arrays" }, { "code": null, "e": 8517, "s": 8512, "text": "Java" }, { "code": null, "e": 8531, "s": 8517, "text": "Java Programs" }, { "code": null, "e": 8541, "s": 8531, "text": "Searching" }, { "code": null, "e": 8548, "s": 8541, "text": "Amazon" }, { "code": null, "e": 8555, "s": 8548, "text": "Arrays" }, { "code": null, "e": 8565, "s": 8555, "text": "Searching" }, { "code": null, "e": 8570, "s": 8565, "text": "Java" }, { "code": null, "e": 8668, "s": 8570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8700, "s": 8668, "text": "Introduction to Data Structures" }, { "code": null, "e": 8725, "s": 8700, "text": "Window Sliding Technique" }, { "code": null, "e": 8772, "s": 8725, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8803, "s": 8772, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8861, "s": 8803, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 8905, "s": 8861, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8941, "s": 8905, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8966, "s": 8941, "text": "Reverse a string in Java" }, { "code": null, "e": 9017, "s": 8966, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
HTML | DOM outerHTML property
11 Jun, 2020 The outerHTML property of the DOM interface gives the HTML fragment of that element. It not only gives the content, but the whole HTML structure of the element. It can also be used to replace the HTML structure of the element. Syntax: To return the outerHTML.var value = element.outerHTML; var value = element.outerHTML; To set the outerHTML.element.outerHTML = "HTML_Structure"; element.outerHTML = "HTML_Structure"; Return value: When getting outerHTML, it returns HTML String data. Example 1: This example shows how to get the outerHTML of an element with id=“gfg”. HTML <!DOCTYPE html><html> <head> <title>GeeksforGeeks</title></head> <body> <div id="gfg"> <h1>GeeksforGeeks</h1> <p>Welcome geeks!</p> </div> <script> var g = document.getElementById("gfg"); document.write(g.outerHTML); </script></body> </html> Output: The outerHTML of element can be seen in the output: Example 2: This example shows how to set or change the outerHTML. HTML <!DOCTYPE html><html> <head> <title>GeeksforGeeks</title></head> <body> <h1>GeeksforGeeks</h1> <div id="d"> Click on Button to change the outerHTML. </div> <br> <button onclick="changeouter()">click</button> <script> function changeouter() { var gfg = document.getElementById("d"); gfg.outerHTML = "<h3>Hey Geeks! outerHTML is changed</h3>"; } </script></body> </html> Output: Before clicking the button: After clicking the button: HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2020" }, { "code": null, "e": 255, "s": 28, "text": "The outerHTML property of the DOM interface gives the HTML fragment of that element. It not only gives the content, but the whole HTML structure of the element. It can also be used to replace the HTML structure of the element." }, { "code": null, "e": 263, "s": 255, "text": "Syntax:" }, { "code": null, "e": 318, "s": 263, "text": "To return the outerHTML.var value = element.outerHTML;" }, { "code": null, "e": 349, "s": 318, "text": "var value = element.outerHTML;" }, { "code": null, "e": 408, "s": 349, "text": "To set the outerHTML.element.outerHTML = \"HTML_Structure\";" }, { "code": null, "e": 446, "s": 408, "text": "element.outerHTML = \"HTML_Structure\";" }, { "code": null, "e": 513, "s": 446, "text": "Return value: When getting outerHTML, it returns HTML String data." }, { "code": null, "e": 597, "s": 513, "text": "Example 1: This example shows how to get the outerHTML of an element with id=“gfg”." }, { "code": null, "e": 602, "s": 597, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title></head> <body> <div id=\"gfg\"> <h1>GeeksforGeeks</h1> <p>Welcome geeks!</p> </div> <script> var g = document.getElementById(\"gfg\"); document.write(g.outerHTML); </script></body> </html>", "e": 898, "s": 602, "text": null }, { "code": null, "e": 906, "s": 898, "text": "Output:" }, { "code": null, "e": 958, "s": 906, "text": "The outerHTML of element can be seen in the output:" }, { "code": null, "e": 1024, "s": 958, "text": "Example 2: This example shows how to set or change the outerHTML." }, { "code": null, "e": 1029, "s": 1024, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title></head> <body> <h1>GeeksforGeeks</h1> <div id=\"d\"> Click on Button to change the outerHTML. </div> <br> <button onclick=\"changeouter()\">click</button> <script> function changeouter() { var gfg = document.getElementById(\"d\"); gfg.outerHTML = \"<h3>Hey Geeks! outerHTML is changed</h3>\"; } </script></body> </html>", "e": 1487, "s": 1029, "text": null }, { "code": null, "e": 1495, "s": 1487, "text": "Output:" }, { "code": null, "e": 1523, "s": 1495, "text": "Before clicking the button:" }, { "code": null, "e": 1550, "s": 1523, "text": "After clicking the button:" }, { "code": null, "e": 1560, "s": 1550, "text": "HTML-Misc" }, { "code": null, "e": 1576, "s": 1560, "text": "JavaScript-Misc" }, { "code": null, "e": 1581, "s": 1576, "text": "HTML" }, { "code": null, "e": 1592, "s": 1581, "text": "JavaScript" }, { "code": null, "e": 1609, "s": 1592, "text": "Web Technologies" }, { "code": null, "e": 1614, "s": 1609, "text": "HTML" }, { "code": null, "e": 1712, "s": 1614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1736, "s": 1712, "text": "REST API (Introduction)" }, { "code": null, "e": 1775, "s": 1736, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1814, "s": 1775, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1851, "s": 1814, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1871, "s": 1851, "text": "Angular File Upload" }, { "code": null, "e": 1932, "s": 1871, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2004, "s": 1932, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2044, "s": 2004, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2096, "s": 2044, "text": "How to append HTML code to a div using JavaScript ?" } ]
Matplotlib.axes.Axes.get_label() in Python
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.get_label() function in axes module of matplotlib library is used to get the label used for this artist in the legend. Syntax: Axes.get_label(self) Parameters: This method does not accepts any parameter. Returns: This method return the label used for this artist in the legend. Below examples illustrate the matplotlib.axes.Axes.get_label() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() x = [0, 1]y = [1, 1]line, = ax.plot(x, y)ax.legend(("Line_1", )) ax.text(0.2, 1.02, "Value Return by get_label()\: " + str(line.get_label())) fig.suptitle('matplotlib.axes.Axes.get_label() function\Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as plt def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) fig, host = plt.subplots()fig.subplots_adjust(right = 0.75) par1 = host.twinx()par2 = host.twinx() # Offset the right spine of par2.# The ticks and label have already been# placed on the right by twinx above.par2.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, par2 has# its frame off, so the line of its# detached spine is invisible. First,# activate the frame but make the patch# and spines invisible.make_patch_spines_invisible(par2) # Second, show the right spine.par2.spines["right"].set_visible(True) p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label ="Y-label 1")p2, = par1.plot([0, 1, 2], [0, 30, 20], "r-", label ="Y-label 2")p3, = par2.plot([0, 1, 2], [500, 300, 150], "g-", label ="Y-label 3") host.set_xlim(0.25, 1.75)host.set_ylim(0.25, 1.75)par1.set_ylim(0, 40)par2.set_ylim(10, 500) host.set_xlabel("X-label")host.set_ylabel("Y-label 1")par1.set_ylabel("Y-label 2")par2.set_ylabel("Y-label 3") host.yaxis.label.set_color(p1.get_color())par1.yaxis.label.set_color(p2.get_color())par2.yaxis.label.set_color(p3.get_color()) tkw = dict(size = 4, width = 1.5)host.tick_params(axis ='y', colors = p1.get_color(), **tkw)par1.tick_params(axis ='y', colors = p2.get_color(), **tkw)par2.tick_params(axis ='y', colors = p3.get_color(), **tkw)host.tick_params(axis ='x', **tkw) lines = [p1, p2, p3] host.legend(lines, [l.get_label() for l in lines]) fig.suptitle('matplotlib.axes.Axes.get_label()\function Example\n\n', fontweight ="bold") plt.show() Output:Diagram: Matplotlib axes-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Deque in Python Stack in Python Queue in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 456, "s": 328, "text": "The Axes.get_label() function in axes module of matplotlib library is used to get the label used for this artist in the legend." }, { "code": null, "e": 485, "s": 456, "text": "Syntax: Axes.get_label(self)" }, { "code": null, "e": 541, "s": 485, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 615, "s": 541, "text": "Returns: This method return the label used for this artist in the legend." }, { "code": null, "e": 707, "s": 615, "text": "Below examples illustrate the matplotlib.axes.Axes.get_label() function in matplotlib.axes:" }, { "code": null, "e": 718, "s": 707, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() x = [0, 1]y = [1, 1]line, = ax.plot(x, y)ax.legend((\"Line_1\", )) ax.text(0.2, 1.02, \"Value Return by get_label()\\: \" + str(line.get_label())) fig.suptitle('matplotlib.axes.Axes.get_label() function\\Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 1065, "s": 718, "text": null }, { "code": null, "e": 1073, "s": 1065, "text": "Output:" }, { "code": null, "e": 1084, "s": 1073, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) fig, host = plt.subplots()fig.subplots_adjust(right = 0.75) par1 = host.twinx()par2 = host.twinx() # Offset the right spine of par2.# The ticks and label have already been# placed on the right by twinx above.par2.spines[\"right\"].set_position((\"axes\", 1.2)) # Having been created by twinx, par2 has# its frame off, so the line of its# detached spine is invisible. First,# activate the frame but make the patch# and spines invisible.make_patch_spines_invisible(par2) # Second, show the right spine.par2.spines[\"right\"].set_visible(True) p1, = host.plot([0, 1, 2], [0, 1, 2], \"b-\", label =\"Y-label 1\")p2, = par1.plot([0, 1, 2], [0, 30, 20], \"r-\", label =\"Y-label 2\")p3, = par2.plot([0, 1, 2], [500, 300, 150], \"g-\", label =\"Y-label 3\") host.set_xlim(0.25, 1.75)host.set_ylim(0.25, 1.75)par1.set_ylim(0, 40)par2.set_ylim(10, 500) host.set_xlabel(\"X-label\")host.set_ylabel(\"Y-label 1\")par1.set_ylabel(\"Y-label 2\")par2.set_ylabel(\"Y-label 3\") host.yaxis.label.set_color(p1.get_color())par1.yaxis.label.set_color(p2.get_color())par2.yaxis.label.set_color(p3.get_color()) tkw = dict(size = 4, width = 1.5)host.tick_params(axis ='y', colors = p1.get_color(), **tkw)par1.tick_params(axis ='y', colors = p2.get_color(), **tkw)par2.tick_params(axis ='y', colors = p3.get_color(), **tkw)host.tick_params(axis ='x', **tkw) lines = [p1, p2, p3] host.legend(lines, [l.get_label() for l in lines]) fig.suptitle('matplotlib.axes.Axes.get_label()\\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 2986, "s": 1084, "text": null }, { "code": null, "e": 3002, "s": 2986, "text": "Output:Diagram:" }, { "code": null, "e": 3024, "s": 3002, "text": "Matplotlib axes-class" }, { "code": null, "e": 3042, "s": 3024, "text": "Python-matplotlib" }, { "code": null, "e": 3049, "s": 3042, "text": "Python" }, { "code": null, "e": 3147, "s": 3049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3192, "s": 3147, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3214, "s": 3192, "text": "Enumerate() in Python" }, { "code": null, "e": 3264, "s": 3214, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 3282, "s": 3264, "text": "Python Dictionary" }, { "code": null, "e": 3298, "s": 3282, "text": "Deque in Python" }, { "code": null, "e": 3314, "s": 3298, "text": "Stack in Python" }, { "code": null, "e": 3330, "s": 3314, "text": "Queue in Python" }, { "code": null, "e": 3352, "s": 3330, "text": "Defaultdict in Python" }, { "code": null, "e": 3394, "s": 3352, "text": "Different ways to create Pandas Dataframe" } ]
Puzzle | 1000 light bulbs switched on/off by 1000 people passing by
05 Jul, 2021 There are 1000 light bulbs and 1000 people. All light bulbs are initially off. Person 1 goes flipping light bulb 1, 2, 3, 4, ... person 2 then flips 2, 4, 6, 8, ... person 3 then 3, 6, 9, ... etc until all 1000 persons have done this. What is the status of light bulbs 25, 93, 576, 132, 605, 26, 45, 37, 36 after all people have flipped their respective light bulbs? Is there a general solution to predict the status of a light bulb? How many light bulbs are on after all 1000 people have gone by? Explanation: The key observations are: Person 1 flips the light bulb 1, 2, 3, ... which are multiples of 1. Person 2 flips the light bulb 2, 4, 6, ... which are multiples of 2. Person 3 flips the light bulb 3, 6, 9, ... which are multiples of 3. Similarly, Person 1000 flips the light bulb 1000, which is a multiple of 1000. From the above observations, we can say that person i will flip light bulbs which are multiples of i, Thus, a light bulb j will be flipped by all persons for whom j is a multiple of their person number. In other words, light bulb j will be flipped by all people whose for person number i is a factor of j, Examples: (i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. (ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. Thus, light bulb 25 will be flipped by persons 1, 5, 25, so it will be flipped 3 times, which is odd and since initially, all bulbs were “off”, now light bulb 25 will be “on”. The light bulb 93 will be flipped by persons 1, 3, 31, 93, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 93 will be “off”. The light bulb 576 will be flipped by persons 1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 32, 36, 48, 64, 72, 96, 144, 192, 288, 576, so it will be flipped 21 times, which is odd and since initially, all bulbs were “off”, now light bulb 576 will be “on”. The light bulb 132 will be flipped by persons 1, 2, 3, 4, 6, 11, 12, 22, 33, 44, 66, 132, so it will be flipped 12 times, which is even and since initially, all bulbs were “off”, now light bulb 132 will be “off”. The light bulb 605 will be flipped by persons 1, 5, 11, 55, 121, 605, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 605 will be “off”. The light bulb 26 will be flipped by persons 1, 2, 13, 26, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 26 will be “off”. The light bulb 45 will be flipped by persons 1, 3, 5, 9, 15, 45, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 45 will be “off”. The light bulb 37, being the prime numbered bulb, will be flipped by persons 1, 37, so it will be flipped 2 times, which is even and since initially, all bulbs were “off”, now light bulb 37 will be “off”. The light bulb 36 will be flipped by persons 1, 2, 3, 4, 6, 9, 12, 18, 36, so it will be flipped 9 times, which is odd and, since initially, all bulbs were “off”, now light bulb 36 will be “on”. Person 1 flips the light bulb 1, 2, 3, ... which are multiples of 1. Person 2 flips the light bulb 2, 4, 6, ... which are multiples of 2. Person 3 flips the light bulb 3, 6, 9, ... which are multiples of 3. Similarly, Person 1000 flips the light bulb 1000, which is a multiple of 1000. From the above observations, we can say that person i will flip light bulbs which are multiples of i, Thus, a light bulb j will be flipped by all persons for whom j is a multiple of their person number. In other words, light bulb j will be flipped by all people whose for person number i is a factor of j, Examples: (i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. (ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. (i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. (ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. Thus, light bulb 25 will be flipped by persons 1, 5, 25, so it will be flipped 3 times, which is odd and since initially, all bulbs were “off”, now light bulb 25 will be “on”. The light bulb 93 will be flipped by persons 1, 3, 31, 93, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 93 will be “off”. The light bulb 576 will be flipped by persons 1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 32, 36, 48, 64, 72, 96, 144, 192, 288, 576, so it will be flipped 21 times, which is odd and since initially, all bulbs were “off”, now light bulb 576 will be “on”. The light bulb 132 will be flipped by persons 1, 2, 3, 4, 6, 11, 12, 22, 33, 44, 66, 132, so it will be flipped 12 times, which is even and since initially, all bulbs were “off”, now light bulb 132 will be “off”. The light bulb 605 will be flipped by persons 1, 5, 11, 55, 121, 605, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 605 will be “off”. The light bulb 26 will be flipped by persons 1, 2, 13, 26, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 26 will be “off”. The light bulb 45 will be flipped by persons 1, 3, 5, 9, 15, 45, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 45 will be “off”. The light bulb 37, being the prime numbered bulb, will be flipped by persons 1, 37, so it will be flipped 2 times, which is even and since initially, all bulbs were “off”, now light bulb 37 will be “off”. The light bulb 36 will be flipped by persons 1, 2, 3, 4, 6, 9, 12, 18, 36, so it will be flipped 9 times, which is odd and, since initially, all bulbs were “off”, now light bulb 36 will be “on”. To find out the status of a given light bulb: We count the number of factors of the light bulb number, and as per the above observations, if the number of factors is odd, then the light bulb will be “on”, and if it’s even, then it will be “off” in the end.Algorithm to find how many light bulbs will be “on” in the end: We count the factors of each number from 1 to 1000. If the number of factors for any number is odd, the corresponding light bulb is “on” so we update the result, and finally, print it. Below is the code implementing the above algorithm. C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <iostream>using namespace std; int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be "on" in the end cout << "Light bulb " << bulb << " will be on" << "\n"; onBulbs++; } } return onBulbs;} // Driver program to test above functionint main(){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); cout << "Total " << onBulbs << " light bulbs will be on in the end out of " << numberOfBulbs << " light bulbs" << "\n"; return 0;} // Java implementation of the// above given approachpublic class GFG{ static int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be "on" in the end System.out.println("Light bulb " + bulb + " will be on"); onBulbs++; } } return onBulbs;} // Driver program to test above functionpublic static void main(String [] args){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); System.out.println("Total " + onBulbs + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs");} // This code is contributed// by Ryuga} # Python3 code implementing the# given approach def findOnBulbs(numberOfBulbs): # initializing the result onBulbs = 0 # to loop over all bulbs from # 1 to numberOfBulbs bulb = 1 # to loop over persons to check # whether their person number person = 1 # Is a factor of light bulb number or not for bulb in range(1, numberOfBulbs + 1): # inner loop to find factors of # given bulb to count the number # of factors of a given bulb factors = 0 for person in range(1, int(numberOfBulbs**(0.5)) + 1): if bulb % person == 0: # person is a factor factors += 1 # bulb != person*person if bulb // person != person: factors += 1 # if number of factors is odd, then the if factors % 2 == 1: # light bulb will be "on" in the end print("Light bulb", bulb, "will be on") onBulbs += 1 return onBulbs # Driver Codeif __name__ == "__main__": # total number of light bulbs numberOfBulbs = 1000 # to find number of on bulbs in # the end after all persons have # flipped the light bulbs onBulbs = findOnBulbs(numberOfBulbs) print("Total", onBulbs, "light bulbs will", "be on in the end out of", numberOfBulbs, "light bulbs") # This code is contributed# by Rituraj Jain // C# implementation of above approachusing System;class GFG{ static int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be "on" in the end Console.WriteLine("Light bulb " + bulb + " will be on"); onBulbs++; } } return onBulbs;} // Driver program to test above functionpublic static void Main(){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); Console.WriteLine("Total " + onBulbs + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs");}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of above approach function findOnBulbs($numberOfBulbs){ // initializing the result $onBulbs = 0; // to loop over all bulbs from // 1 to numberOfBulbs $bulb = 1; // to loop over persons to check // whether their person number $person = 1; // is a factor of light bulb number or not for ($bulb = 1; $bulb <= $numberOfBulbs; $bulb++) { // inner loop to find factors of given // bulb to count the number of factors // of a given bulb $factors = 0; for ($person = 1; $person * $person <= $numberOfBulbs; $person++) { if ($bulb % $person == 0) // person is a factor { $factors++; // bulb != person*person if ($bulb / $person != $person) { $factors++; } } } // if number of factors is odd, then the if ($factors % 2 == 1) { // light bulb will be "on" in the end echo "Light bulb " . $bulb . " will be on" ."\n"; $onBulbs++; } } return $onBulbs;} // Driver Code // total number of light bulbs$numberOfBulbs = 1000; // to find number of on bulbs in// the end after all persons have// flipped the light bulbs$onBulbs = findOnBulbs($numberOfBulbs); echo "Total " . $onBulbs . " light bulbs will " . "be on in the end out of " . $numberOfBulbs . " light bulbs" ."\n"; // This code is contributed by ita_c?> <script>// Javascript implementation of the// above given approach function findOnBulbs(numberOfBulbs){ // initializing the result let onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs let bulb = 1; // to loop over persons to check whether their person number let person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb let factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be "on" in the end document.write("Light bulb " + bulb + " will be on<br>"); onBulbs++; } } return onBulbs;} // Driver program to test above function// total number of light bulbslet numberOfBulbs = 1000; // to find number of on bulbs in// the end after all persons have// flipped the light bulbslet onBulbs = findOnBulbs(numberOfBulbs); document.write("Total " + onBulbs + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs"); // This code is contributed by avanitrachhadiya2155</script> The previous program is written in O(n*sqrt(n)). From observation, it is clear that whenever the number of factors is odd, the bulb will be on. For any non-square number with each divisor, there is a corresponding quotient, so the number of factors will be even. For every square number, when we divide it by its square root, the quotient will be the same number, i.e. its square root. So it has an odd number of factors. Therefore, we can write an efficient code for this problem which computes in O(sqrt(n)). C++ Java Python3 C# Javascript #include<iostream>#include<math.h>using namespace std; int main(){ int numberOfBulbs = 1000; int root = sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { cout << "Light bulb " << (i * i) << " will be on" << endl; } cout << "Total " << root << " light bulbs will be on in the end out of " << numberOfBulbs << " light bulbs" << endl; return 0;} // This code is contributed by Apurvaraj import java.io.*; class GFG { // Driver code public static void main (String[] args) { int numberOfBulbs = 1000; int root = (int) Math.sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { System.out.println("Light bulb " + (i * i) +" will be on"); } System.out.println("Total " + root + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs"); }} // This code is contributed b ab2127. import mathroot = int(math.sqrt(1000)) for i in range(1, root + 1): print("Light bulb %d will be on"%(i * i)) print("""Total %d light bulbs will be onin the end out of 1000 light bulbs"""%root) using System;using System.Collections.Generic; class GFG{ // Driver code public static void Main(String [] args){ int numberOfBulbs = 1000; int root = (int) Math.Sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { Console.WriteLine("Light bulb " + (i * i) +" will be on"); } Console.WriteLine("Total " + root + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs");}} // This code is contributed by 29AjayKumar <script> var numberOfBulbs = 1000; var root = parseInt( Math.sqrt(numberOfBulbs)); for (i = 1; i < root + 1; i++) { document.write("Light bulb " + (i * i) + " will be on<br/>"); } document.write( "Total " + root + " light bulbs will be on in the end out of " + numberOfBulbs + " light bulbs<br/>"); // This code is contributed by Rajput-Ji</script> Output: Light bulb 1 will be on Light bulb 4 will be on Light bulb 9 will be on Light bulb 16 will be on Light bulb 25 will be on Light bulb 36 will be on Light bulb 49 will be on Light bulb 64 will be on Light bulb 81 will be on Light bulb 100 will be on Light bulb 121 will be on Light bulb 144 will be on Light bulb 169 will be on Light bulb 196 will be on Light bulb 225 will be on Light bulb 256 will be on Light bulb 289 will be on Light bulb 324 will be on Light bulb 361 will be on Light bulb 400 will be on Light bulb 441 will be on Light bulb 484 will be on Light bulb 529 will be on Light bulb 576 will be on Light bulb 625 will be on Light bulb 676 will be on Light bulb 729 will be on Light bulb 784 will be on Light bulb 841 will be on Light bulb 900 will be on Light bulb 961 will be on Total 31 light bulbs will be on in the end out of 1000 light bulbs rituraj_jain Akanksha_Rai ankthon ukasp ANKITKUMAR34 ApurvaRaj madarsh986 29AjayKumar Rajput-Ji avanitrachhadiya2155 ab2127 combionatrics Permutation and Combination Puzzles Technical Scripter 2018 Puzzles Technical Scripter Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2021" }, { "code": null, "e": 552, "s": 54, "text": "There are 1000 light bulbs and 1000 people. All light bulbs are initially off. Person 1 goes flipping light bulb 1, 2, 3, 4, ... person 2 then flips 2, 4, 6, 8, ... person 3 then 3, 6, 9, ... etc until all 1000 persons have done this. What is the status of light bulbs 25, 93, 576, 132, 605, 26, 45, 37, 36 after all people have flipped their respective light bulbs? Is there a general solution to predict the status of a light bulb? How many light bulbs are on after all 1000 people have gone by?" }, { "code": null, "e": 593, "s": 552, "text": "Explanation: The key observations are: " }, { "code": null, "e": 3189, "s": 593, "text": "Person 1 flips the light bulb 1, 2, 3, ... which are multiples of 1. Person 2 flips the light bulb 2, 4, 6, ... which are multiples of 2. Person 3 flips the light bulb 3, 6, 9, ... which are multiples of 3. Similarly, Person 1000 flips the light bulb 1000, which is a multiple of 1000. From the above observations, we can say that person i will flip light bulbs which are multiples of i, Thus, a light bulb j will be flipped by all persons for whom j is a multiple of their person number. In other words, light bulb j will be flipped by all people whose for person number i is a factor of j, Examples: (i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. (ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. Thus, light bulb 25 will be flipped by persons 1, 5, 25, so it will be flipped 3 times, which is odd and since initially, all bulbs were “off”, now light bulb 25 will be “on”. The light bulb 93 will be flipped by persons 1, 3, 31, 93, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 93 will be “off”. The light bulb 576 will be flipped by persons 1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 32, 36, 48, 64, 72, 96, 144, 192, 288, 576, so it will be flipped 21 times, which is odd and since initially, all bulbs were “off”, now light bulb 576 will be “on”. The light bulb 132 will be flipped by persons 1, 2, 3, 4, 6, 11, 12, 22, 33, 44, 66, 132, so it will be flipped 12 times, which is even and since initially, all bulbs were “off”, now light bulb 132 will be “off”. The light bulb 605 will be flipped by persons 1, 5, 11, 55, 121, 605, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 605 will be “off”. The light bulb 26 will be flipped by persons 1, 2, 13, 26, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 26 will be “off”. The light bulb 45 will be flipped by persons 1, 3, 5, 9, 15, 45, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 45 will be “off”. The light bulb 37, being the prime numbered bulb, will be flipped by persons 1, 37, so it will be flipped 2 times, which is even and since initially, all bulbs were “off”, now light bulb 37 will be “off”. The light bulb 36 will be flipped by persons 1, 2, 3, 4, 6, 9, 12, 18, 36, so it will be flipped 9 times, which is odd and, since initially, all bulbs were “off”, now light bulb 36 will be “on”. " }, { "code": null, "e": 3260, "s": 3189, "text": "Person 1 flips the light bulb 1, 2, 3, ... which are multiples of 1. " }, { "code": null, "e": 3331, "s": 3260, "text": "Person 2 flips the light bulb 2, 4, 6, ... which are multiples of 2. " }, { "code": null, "e": 3402, "s": 3331, "text": "Person 3 flips the light bulb 3, 6, 9, ... which are multiples of 3. " }, { "code": null, "e": 3483, "s": 3402, "text": "Similarly, Person 1000 flips the light bulb 1000, which is a multiple of 1000. " }, { "code": null, "e": 3587, "s": 3483, "text": "From the above observations, we can say that person i will flip light bulbs which are multiples of i, " }, { "code": null, "e": 3793, "s": 3587, "text": "Thus, a light bulb j will be flipped by all persons for whom j is a multiple of their person number. In other words, light bulb j will be flipped by all people whose for person number i is a factor of j, " }, { "code": null, "e": 4007, "s": 3793, "text": "Examples: (i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. (ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. " }, { "code": null, "e": 4106, "s": 4007, "text": "(i) Light Bulb 10 will be flipped by persons 1, 2, 5, 10 whose person numbers are factors of 10. " }, { "code": null, "e": 4212, "s": 4106, "text": "(ii) Light Bulb 12 will be flipped by persons 1, 2, 3, 4, 6, 12 whose person numbers are factors of 12. " }, { "code": null, "e": 4390, "s": 4212, "text": "Thus, light bulb 25 will be flipped by persons 1, 5, 25, so it will be flipped 3 times, which is odd and since initially, all bulbs were “off”, now light bulb 25 will be “on”. " }, { "code": null, "e": 4572, "s": 4390, "text": "The light bulb 93 will be flipped by persons 1, 3, 31, 93, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 93 will be “off”. " }, { "code": null, "e": 4822, "s": 4572, "text": "The light bulb 576 will be flipped by persons 1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 32, 36, 48, 64, 72, 96, 144, 192, 288, 576, so it will be flipped 21 times, which is odd and since initially, all bulbs were “off”, now light bulb 576 will be “on”. " }, { "code": null, "e": 5037, "s": 4822, "text": "The light bulb 132 will be flipped by persons 1, 2, 3, 4, 6, 11, 12, 22, 33, 44, 66, 132, so it will be flipped 12 times, which is even and since initially, all bulbs were “off”, now light bulb 132 will be “off”. " }, { "code": null, "e": 5231, "s": 5037, "text": "The light bulb 605 will be flipped by persons 1, 5, 11, 55, 121, 605, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 605 will be “off”. " }, { "code": null, "e": 5413, "s": 5231, "text": "The light bulb 26 will be flipped by persons 1, 2, 13, 26, so it will be flipped 4 times, which is even and since initially, all bulbs were “off”, now light bulb 26 will be “off”. " }, { "code": null, "e": 5601, "s": 5413, "text": "The light bulb 45 will be flipped by persons 1, 3, 5, 9, 15, 45, so it will be flipped 6 times, which is even and since initially, all bulbs were “off”, now light bulb 45 will be “off”. " }, { "code": null, "e": 5808, "s": 5601, "text": "The light bulb 37, being the prime numbered bulb, will be flipped by persons 1, 37, so it will be flipped 2 times, which is even and since initially, all bulbs were “off”, now light bulb 37 will be “off”. " }, { "code": null, "e": 6005, "s": 5808, "text": "The light bulb 36 will be flipped by persons 1, 2, 3, 4, 6, 9, 12, 18, 36, so it will be flipped 9 times, which is odd and, since initially, all bulbs were “off”, now light bulb 36 will be “on”. " }, { "code": null, "e": 6511, "s": 6005, "text": "To find out the status of a given light bulb: We count the number of factors of the light bulb number, and as per the above observations, if the number of factors is odd, then the light bulb will be “on”, and if it’s even, then it will be “off” in the end.Algorithm to find how many light bulbs will be “on” in the end: We count the factors of each number from 1 to 1000. If the number of factors for any number is odd, the corresponding light bulb is “on” so we update the result, and finally, print it. " }, { "code": null, "e": 6563, "s": 6511, "text": "Below is the code implementing the above algorithm." }, { "code": null, "e": 6567, "s": 6563, "text": "C++" }, { "code": null, "e": 6572, "s": 6567, "text": "Java" }, { "code": null, "e": 6580, "s": 6572, "text": "Python3" }, { "code": null, "e": 6583, "s": 6580, "text": "C#" }, { "code": null, "e": 6587, "s": 6583, "text": "PHP" }, { "code": null, "e": 6598, "s": 6587, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>using namespace std; int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be \"on\" in the end cout << \"Light bulb \" << bulb << \" will be on\" << \"\\n\"; onBulbs++; } } return onBulbs;} // Driver program to test above functionint main(){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); cout << \"Total \" << onBulbs << \" light bulbs will be on in the end out of \" << numberOfBulbs << \" light bulbs\" << \"\\n\"; return 0;}", "e": 8332, "s": 6598, "text": null }, { "code": "// Java implementation of the// above given approachpublic class GFG{ static int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be \"on\" in the end System.out.println(\"Light bulb \" + bulb + \" will be on\"); onBulbs++; } } return onBulbs;} // Driver program to test above functionpublic static void main(String [] args){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); System.out.println(\"Total \" + onBulbs + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs\");} // This code is contributed// by Ryuga}", "e": 10056, "s": 8332, "text": null }, { "code": "# Python3 code implementing the# given approach def findOnBulbs(numberOfBulbs): # initializing the result onBulbs = 0 # to loop over all bulbs from # 1 to numberOfBulbs bulb = 1 # to loop over persons to check # whether their person number person = 1 # Is a factor of light bulb number or not for bulb in range(1, numberOfBulbs + 1): # inner loop to find factors of # given bulb to count the number # of factors of a given bulb factors = 0 for person in range(1, int(numberOfBulbs**(0.5)) + 1): if bulb % person == 0: # person is a factor factors += 1 # bulb != person*person if bulb // person != person: factors += 1 # if number of factors is odd, then the if factors % 2 == 1: # light bulb will be \"on\" in the end print(\"Light bulb\", bulb, \"will be on\") onBulbs += 1 return onBulbs # Driver Codeif __name__ == \"__main__\": # total number of light bulbs numberOfBulbs = 1000 # to find number of on bulbs in # the end after all persons have # flipped the light bulbs onBulbs = findOnBulbs(numberOfBulbs) print(\"Total\", onBulbs, \"light bulbs will\", \"be on in the end out of\", numberOfBulbs, \"light bulbs\") # This code is contributed# by Rituraj Jain", "e": 11553, "s": 10056, "text": null }, { "code": "// C# implementation of above approachusing System;class GFG{ static int findOnBulbs(int numberOfBulbs){ // initializing the result int onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs int bulb = 1; // to loop over persons to check whether their person number int person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb int factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be \"on\" in the end Console.WriteLine(\"Light bulb \" + bulb + \" will be on\"); onBulbs++; } } return onBulbs;} // Driver program to test above functionpublic static void Main(){ // total number of light bulbs int numberOfBulbs = 1000; // to find number of on bulbs in // the end after all persons have // flipped the light bulbs int onBulbs = findOnBulbs(numberOfBulbs); Console.WriteLine(\"Total \" + onBulbs + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs\");}} // This code is contributed// by Akanksha Rai", "e": 13260, "s": 11553, "text": null }, { "code": "<?php// PHP implementation of above approach function findOnBulbs($numberOfBulbs){ // initializing the result $onBulbs = 0; // to loop over all bulbs from // 1 to numberOfBulbs $bulb = 1; // to loop over persons to check // whether their person number $person = 1; // is a factor of light bulb number or not for ($bulb = 1; $bulb <= $numberOfBulbs; $bulb++) { // inner loop to find factors of given // bulb to count the number of factors // of a given bulb $factors = 0; for ($person = 1; $person * $person <= $numberOfBulbs; $person++) { if ($bulb % $person == 0) // person is a factor { $factors++; // bulb != person*person if ($bulb / $person != $person) { $factors++; } } } // if number of factors is odd, then the if ($factors % 2 == 1) { // light bulb will be \"on\" in the end echo \"Light bulb \" . $bulb . \" will be on\" .\"\\n\"; $onBulbs++; } } return $onBulbs;} // Driver Code // total number of light bulbs$numberOfBulbs = 1000; // to find number of on bulbs in// the end after all persons have// flipped the light bulbs$onBulbs = findOnBulbs($numberOfBulbs); echo \"Total \" . $onBulbs . \" light bulbs will \" . \"be on in the end out of \" . $numberOfBulbs . \" light bulbs\" .\"\\n\"; // This code is contributed by ita_c?>", "e": 14917, "s": 13260, "text": null }, { "code": "<script>// Javascript implementation of the// above given approach function findOnBulbs(numberOfBulbs){ // initializing the result let onBulbs = 0; // to loop over all bulbs from 1 to numberOfBulbs let bulb = 1; // to loop over persons to check whether their person number let person = 1; // is a factor of light bulb number or not for (bulb = 1; bulb <= numberOfBulbs; bulb++) { // inner loop to find factors of given bulb // to count the number of factors of a given bulb let factors = 0; for (person = 1; person * person <= numberOfBulbs; person++) { if (bulb % person == 0) // person is a factor { factors++; // bulb != person*person if (bulb / person != person) { factors++; } } } // if number of factors is odd, then the if (factors % 2 == 1) { // light bulb will be \"on\" in the end document.write(\"Light bulb \" + bulb + \" will be on<br>\"); onBulbs++; } } return onBulbs;} // Driver program to test above function// total number of light bulbslet numberOfBulbs = 1000; // to find number of on bulbs in// the end after all persons have// flipped the light bulbslet onBulbs = findOnBulbs(numberOfBulbs); document.write(\"Total \" + onBulbs + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 16609, "s": 14917, "text": null }, { "code": null, "e": 16659, "s": 16609, "text": "The previous program is written in O(n*sqrt(n)). " }, { "code": null, "e": 17033, "s": 16659, "text": "From observation, it is clear that whenever the number of factors is odd, the bulb will be on. For any non-square number with each divisor, there is a corresponding quotient, so the number of factors will be even. For every square number, when we divide it by its square root, the quotient will be the same number, i.e. its square root. So it has an odd number of factors. " }, { "code": null, "e": 17124, "s": 17033, "text": "Therefore, we can write an efficient code for this problem which computes in O(sqrt(n)). " }, { "code": null, "e": 17128, "s": 17124, "text": "C++" }, { "code": null, "e": 17133, "s": 17128, "text": "Java" }, { "code": null, "e": 17141, "s": 17133, "text": "Python3" }, { "code": null, "e": 17144, "s": 17141, "text": "C#" }, { "code": null, "e": 17155, "s": 17144, "text": "Javascript" }, { "code": "#include<iostream>#include<math.h>using namespace std; int main(){ int numberOfBulbs = 1000; int root = sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { cout << \"Light bulb \" << (i * i) << \" will be on\" << endl; } cout << \"Total \" << root << \" light bulbs will be on in the end out of \" << numberOfBulbs << \" light bulbs\" << endl; return 0;} // This code is contributed by Apurvaraj", "e": 17603, "s": 17155, "text": null }, { "code": "import java.io.*; class GFG { // Driver code public static void main (String[] args) { int numberOfBulbs = 1000; int root = (int) Math.sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { System.out.println(\"Light bulb \" + (i * i) +\" will be on\"); } System.out.println(\"Total \" + root + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs\"); }} // This code is contributed b ab2127.", "e": 18099, "s": 17603, "text": null }, { "code": "import mathroot = int(math.sqrt(1000)) for i in range(1, root + 1): print(\"Light bulb %d will be on\"%(i * i)) print(\"\"\"Total %d light bulbs will be onin the end out of 1000 light bulbs\"\"\"%root)", "e": 18300, "s": 18099, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG{ // Driver code public static void Main(String [] args){ int numberOfBulbs = 1000; int root = (int) Math.Sqrt(numberOfBulbs); for (int i = 1; i < root + 1; i++) { Console.WriteLine(\"Light bulb \" + (i * i) +\" will be on\"); } Console.WriteLine(\"Total \" + root + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs\");}} // This code is contributed by 29AjayKumar", "e": 18788, "s": 18300, "text": null }, { "code": "<script> var numberOfBulbs = 1000; var root = parseInt( Math.sqrt(numberOfBulbs)); for (i = 1; i < root + 1; i++) { document.write(\"Light bulb \" + (i * i) + \" will be on<br/>\"); } document.write( \"Total \" + root + \" light bulbs will be on in the end out of \" + numberOfBulbs + \" light bulbs<br/>\"); // This code is contributed by Rajput-Ji</script>", "e": 19219, "s": 18788, "text": null }, { "code": null, "e": 19229, "s": 19219, "text": "Output: " }, { "code": null, "e": 20091, "s": 19229, "text": "Light bulb 1 will be on\nLight bulb 4 will be on\nLight bulb 9 will be on\nLight bulb 16 will be on\nLight bulb 25 will be on\nLight bulb 36 will be on\nLight bulb 49 will be on\nLight bulb 64 will be on\nLight bulb 81 will be on\nLight bulb 100 will be on\nLight bulb 121 will be on\nLight bulb 144 will be on\nLight bulb 169 will be on\nLight bulb 196 will be on\nLight bulb 225 will be on\nLight bulb 256 will be on\nLight bulb 289 will be on\nLight bulb 324 will be on\nLight bulb 361 will be on\nLight bulb 400 will be on\nLight bulb 441 will be on\nLight bulb 484 will be on\nLight bulb 529 will be on\nLight bulb 576 will be on\nLight bulb 625 will be on\nLight bulb 676 will be on\nLight bulb 729 will be on\nLight bulb 784 will be on\nLight bulb 841 will be on\nLight bulb 900 will be on\nLight bulb 961 will be on\nTotal 31 light bulbs will be on in the end out of 1000 light bulbs " }, { "code": null, "e": 20106, "s": 20093, "text": "rituraj_jain" }, { "code": null, "e": 20119, "s": 20106, "text": "Akanksha_Rai" }, { "code": null, "e": 20127, "s": 20119, "text": "ankthon" }, { "code": null, "e": 20133, "s": 20127, "text": "ukasp" }, { "code": null, "e": 20146, "s": 20133, "text": "ANKITKUMAR34" }, { "code": null, "e": 20156, "s": 20146, "text": "ApurvaRaj" }, { "code": null, "e": 20167, "s": 20156, "text": "madarsh986" }, { "code": null, "e": 20179, "s": 20167, "text": "29AjayKumar" }, { "code": null, "e": 20189, "s": 20179, "text": "Rajput-Ji" }, { "code": null, "e": 20210, "s": 20189, "text": "avanitrachhadiya2155" }, { "code": null, "e": 20217, "s": 20210, "text": "ab2127" }, { "code": null, "e": 20231, "s": 20217, "text": "combionatrics" }, { "code": null, "e": 20259, "s": 20231, "text": "Permutation and Combination" }, { "code": null, "e": 20267, "s": 20259, "text": "Puzzles" }, { "code": null, "e": 20291, "s": 20267, "text": "Technical Scripter 2018" }, { "code": null, "e": 20299, "s": 20291, "text": "Puzzles" }, { "code": null, "e": 20318, "s": 20299, "text": "Technical Scripter" }, { "code": null, "e": 20326, "s": 20318, "text": "Puzzles" } ]
What is a PyMongo Cursor?
14 Jun, 2022 MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) that accommodates more data types. When you use the function db.collection.find() to search documents in collections then as a result it returns a pointer. That pointer is known as a cursor. Consider if we have 2 documents in our collection, then the cursor object will point to the first document and then iterate through all documents which are present in our collection. As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB query result sets. This cursor instance is returned by the find() method. Consider the below example for better understanding. Example: Sample database is as follows: javascript from pymongo import MongoClient # Connecting to mongodb client = MongoClient('mongodb://localhost:27017/') with client: db = client.GFG lectures = db.lecture.find() print(lectures.next()) print(lectures.next()) print(lectures.next()) print("\nRemaining Lectures\n") print(list(lectures)) In this, find() method returns the cursor object. lectures = db.lecture.find() With the next() method we get the next document in the collection. lectures.next() With the list() method, we can transform the cursor to a Python list. khushb99 Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jun, 2022" }, { "code": null, "e": 362, "s": 28, "text": "MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) that accommodates more data types." }, { "code": null, "e": 702, "s": 362, "text": "When you use the function db.collection.find() to search documents in collections then as a result it returns a pointer. That pointer is known as a cursor. Consider if we have 2 documents in our collection, then the cursor object will point to the first document and then iterate through all documents which are present in our collection. " }, { "code": null, "e": 921, "s": 702, "text": "As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB query result sets. This cursor instance is returned by the find() method. Consider the below example for better understanding." }, { "code": null, "e": 962, "s": 921, "text": "Example: Sample database is as follows: " }, { "code": null, "e": 976, "s": 965, "text": "javascript" }, { "code": "from pymongo import MongoClient # Connecting to mongodb client = MongoClient('mongodb://localhost:27017/') with client: db = client.GFG lectures = db.lecture.find() print(lectures.next()) print(lectures.next()) print(lectures.next()) print(\"\\nRemaining Lectures\\n\") print(list(lectures))", "e": 1305, "s": 976, "text": null }, { "code": null, "e": 1355, "s": 1305, "text": "In this, find() method returns the cursor object." }, { "code": null, "e": 1384, "s": 1355, "text": "lectures = db.lecture.find()" }, { "code": null, "e": 1451, "s": 1384, "text": "With the next() method we get the next document in the collection." }, { "code": null, "e": 1467, "s": 1451, "text": "lectures.next()" }, { "code": null, "e": 1537, "s": 1467, "text": "With the list() method, we can transform the cursor to a Python list." }, { "code": null, "e": 1546, "s": 1537, "text": "khushb99" }, { "code": null, "e": 1561, "s": 1546, "text": "Python-mongoDB" }, { "code": null, "e": 1568, "s": 1561, "text": "Python" }, { "code": null, "e": 1666, "s": 1568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1698, "s": 1666, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1725, "s": 1698, "text": "Python Classes and Objects" }, { "code": null, "e": 1746, "s": 1725, "text": "Python OOPs Concepts" }, { "code": null, "e": 1769, "s": 1746, "text": "Introduction To PYTHON" }, { "code": null, "e": 1825, "s": 1769, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1867, "s": 1825, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1898, "s": 1867, "text": "Python | os.path.join() method" }, { "code": null, "e": 1940, "s": 1898, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1979, "s": 1940, "text": "Python | Get unique values from a list" } ]
Saving an Image from URL in PHP
31 Jul, 2021 Sometimes, need to download an image from a particular URL and use it into the project. It’s easy to go to the page and use right click button and save the image. But what if you wanted to do it programmatically? The reasons may vary person to person, developer to developer. If set of hundreds of image URLs given and somehow want to save them into the machine, or need to use this concept into the projects. Then definitely not going to download each one of those files manually. There are two different approaches to download image from url which are listed below: Using basic file handling. Using an HTTP library called cURL. Both of these approaches come with their own set of merits and demerits. Using Basic File Handling: This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in “write” mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds. From the script, you can figure out on your own about what it does. Declaring two variables named as $url and $img, representing the source URL and destination file respectively. Use file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file. Use file_get_contents() function to read a file into a string. Example: <?php $url = 'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png'; $img = 'logo.png'; // Function to write image into filefile_put_contents($img, file_get_contents($url)); echo "File downloaded!" ?> File downloaded! Note: It save the image to the server with given name logo.png. Now the only problem with this method is that it requires allow_url_fopen configuration to be set, which is set to 1 by default. But sometimes, project requirements don’t allow to have this option. This may be because of some preventive security measures or just a design principle. In such cases, there is another method to save image. Using HTTP library, cURL: Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library. cURL allows to make HTTP requests in PHP. Start by initializing an instance of it and setting up some of the necessary options for the request, including the URL itself. Then execute this query which returns the content of the file. After that, the rest of the procedure is the same. As soon as we get the data, put it into a file and save it. Approach: In this script, we defined a function file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique. Inside this function, we have initialised an instance of cURL using curl_init function in order to use it for fetching the data. After that, some options need to be set using curl_setopt so that this particular example can work. This function takes three argumentsAn instance of cURLThe corresponding option that need to be setAnd the value to which option is setIn this example, the following options are set:CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly.There is this another option CURLOPT_URL that sets the URL for the request. An instance of cURL The corresponding option that need to be set And the value to which option is set In this example, the following options are set: CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not; CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly. There is this another option CURLOPT_URL that sets the URL for the request. After that, we fetch the data from curl_exec and return it from the parent function. This data is then written on to the file on your machine using file_put_contents. Example: <?php function file_get_contents_curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data;} $data = file_get_contents_curl('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png'); $fp = 'logo-1.png'; file_put_contents( $fp, $data );echo "File downloaded!" ?> Output: File downloaded! This method provides a bit of flexibility while fetching the content from the internet. As mentioned earlier, it is not just limited to HTTP but can be used in many other circumstances as well. It allows to configure the transfer in whatever way you want. For example, file_get_contents uses a simple GET request to fetch the data, but with cURL, can use GET, POST, PUT and other methods as well. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to call PHP function on the click of a Button ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2021" }, { "code": null, "e": 510, "s": 28, "text": "Sometimes, need to download an image from a particular URL and use it into the project. It’s easy to go to the page and use right click button and save the image. But what if you wanted to do it programmatically? The reasons may vary person to person, developer to developer. If set of hundreds of image URLs given and somehow want to save them into the machine, or need to use this concept into the projects. Then definitely not going to download each one of those files manually." }, { "code": null, "e": 596, "s": 510, "text": "There are two different approaches to download image from url which are listed below:" }, { "code": null, "e": 623, "s": 596, "text": "Using basic file handling." }, { "code": null, "e": 658, "s": 623, "text": "Using an HTTP library called cURL." }, { "code": null, "e": 731, "s": 658, "text": "Both of these approaches come with their own set of merits and demerits." }, { "code": null, "e": 1027, "s": 731, "text": "Using Basic File Handling: This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in “write” mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds." }, { "code": null, "e": 1095, "s": 1027, "text": "From the script, you can figure out on your own about what it does." }, { "code": null, "e": 1206, "s": 1095, "text": "Declaring two variables named as $url and $img, representing the source URL and destination file respectively." }, { "code": null, "e": 1368, "s": 1206, "text": "Use file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file." }, { "code": null, "e": 1431, "s": 1368, "text": "Use file_get_contents() function to read a file into a string." }, { "code": null, "e": 1440, "s": 1431, "text": "Example:" }, { "code": "<?php $url = 'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png'; $img = 'logo.png'; // Function to write image into filefile_put_contents($img, file_get_contents($url)); echo \"File downloaded!\" ?>", "e": 1668, "s": 1440, "text": null }, { "code": null, "e": 1685, "s": 1668, "text": "File downloaded!" }, { "code": null, "e": 1749, "s": 1685, "text": "Note: It save the image to the server with given name logo.png." }, { "code": null, "e": 2086, "s": 1749, "text": "Now the only problem with this method is that it requires allow_url_fopen configuration to be set, which is set to 1 by default. But sometimes, project requirements don’t allow to have this option. This may be because of some preventive security measures or just a design principle. In such cases, there is another method to save image." }, { "code": null, "e": 2325, "s": 2086, "text": "Using HTTP library, cURL: Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library." }, { "code": null, "e": 2669, "s": 2325, "text": "cURL allows to make HTTP requests in PHP. Start by initializing an instance of it and setting up some of the necessary options for the request, including the URL itself. Then execute this query which returns the content of the file. After that, the rest of the procedure is the same. As soon as we get the data, put it into a file and save it." }, { "code": null, "e": 2679, "s": 2669, "text": "Approach:" }, { "code": null, "e": 2829, "s": 2679, "text": "In this script, we defined a function file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique." }, { "code": null, "e": 2958, "s": 2829, "text": "Inside this function, we have initialised an instance of cURL using curl_init function in order to use it for fetching the data." }, { "code": null, "e": 3518, "s": 2958, "text": "After that, some options need to be set using curl_setopt so that this particular example can work. This function takes three argumentsAn instance of cURLThe corresponding option that need to be setAnd the value to which option is setIn this example, the following options are set:CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly.There is this another option CURLOPT_URL that sets the URL for the request." }, { "code": null, "e": 3538, "s": 3518, "text": "An instance of cURL" }, { "code": null, "e": 3583, "s": 3538, "text": "The corresponding option that need to be set" }, { "code": null, "e": 3620, "s": 3583, "text": "And the value to which option is set" }, { "code": null, "e": 3668, "s": 3620, "text": "In this example, the following options are set:" }, { "code": null, "e": 3751, "s": 3668, "text": "CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;" }, { "code": null, "e": 3873, "s": 3751, "text": "CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly." }, { "code": null, "e": 3949, "s": 3873, "text": "There is this another option CURLOPT_URL that sets the URL for the request." }, { "code": null, "e": 4034, "s": 3949, "text": "After that, we fetch the data from curl_exec and return it from the parent function." }, { "code": null, "e": 4116, "s": 4034, "text": "This data is then written on to the file on your machine using file_put_contents." }, { "code": null, "e": 4125, "s": 4116, "text": "Example:" }, { "code": "<?php function file_get_contents_curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data;} $data = file_get_contents_curl('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6-1.png'); $fp = 'logo-1.png'; file_put_contents( $fp, $data );echo \"File downloaded!\" ?>", "e": 4584, "s": 4125, "text": null }, { "code": null, "e": 4592, "s": 4584, "text": "Output:" }, { "code": null, "e": 4609, "s": 4592, "text": "File downloaded!" }, { "code": null, "e": 5006, "s": 4609, "text": "This method provides a bit of flexibility while fetching the content from the internet. As mentioned earlier, it is not just limited to HTTP but can be used in many other circumstances as well. It allows to configure the transfer in whatever way you want. For example, file_get_contents uses a simple GET request to fetch the data, but with cURL, can use GET, POST, PUT and other methods as well." }, { "code": null, "e": 5175, "s": 5006, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 5179, "s": 5175, "text": "PHP" }, { "code": null, "e": 5192, "s": 5179, "text": "PHP Programs" }, { "code": null, "e": 5209, "s": 5192, "text": "Web Technologies" }, { "code": null, "e": 5213, "s": 5209, "text": "PHP" }, { "code": null, "e": 5311, "s": 5213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5361, "s": 5311, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5401, "s": 5361, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 5462, "s": 5401, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5512, "s": 5462, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 5557, "s": 5512, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 5607, "s": 5557, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5647, "s": 5607, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 5708, "s": 5647, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5760, "s": 5708, "text": "How to call PHP function on the click of a Button ?" } ]
Maximum possible sum of non-adjacent array elements not exceeding K
01 Jul, 2022 Given an array arr[] consisting of N integers and an integer K, the task is to select some non-adjacent array elements with the maximum possible sum not exceeding K. Examples: Input: arr[] = {50, 10, 20, 30, 40}, K = 100Output: 90Explanation: To maximize the sum that doesn’t exceed K(= 100), select elements 50 and 40.Therefore, maximum possible sum = 90. Input: arr[] = {20, 10, 17, 12, 8, 9}, K = 64Output: 46Explanation: To maximize the sum that doesn’t exceed K(= 64), select elements 20, 17, and 9.Therefore, maximum possible sum = 46. Naive Approach: The simplest approach is to recursively generate all possible subsets of the given array and for each subset, check if it does not contain adjacent elements and has the sum not exceeding K. Among all subsets for which the above condition is found to be true, print the maximum sum obtained for any subset. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximum sum not exceeding// K possible by selecting// a subset of non-adjacent elementsint maxSum(int a[], int n, int k){ // Base Case if (n <= 0) return 0; // Not selecting current // element int option = maxSum(a, n - 1, k); // If selecting current // element is possible if (k >= a[n - 1]) option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Codeint main(){ // Given array arr[] int arr[] = {50, 10, 20, 30, 40}; int N = sizeof(arr) / sizeof(arr[0]); // Given K int K = 100; // Function Call cout << (maxSum(arr, N, K));} // This code is contributed by gauravrajput1 // Java program for the above approach import java.io.*; class GFG { // Function to find the maximum sum // not exceeding K possible by selecting // a subset of non-adjacent elements public static int maxSum( int a[], int n, int k) { // Base Case if (n <= 0) return 0; // Not selecting current element int option = maxSum(a, n - 1, k); // If selecting current element // is possible if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option; } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 50, 10, 20, 30, 40 }; int N = arr.length; // Given K int K = 100; // Function Call System.out.println(maxSum(arr, N, K)); }} # Python3 program for the above approach # Function to find the maximum sum# not exceeding K possible by selecting# a subset of non-adjacent elementsdef maxSum(a, n, k): # Base Case if (n <= 0): return 0 # Not selecting current element option = maxSum(a, n - 1, k) # If selecting current element # is possible if (k >= a[n - 1]): option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])) # Return answer return option # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 50, 10, 20, 30, 40 ] N = len(arr) # Given K K = 100 # Function Call print(maxSum(arr, N, K)) # This code is contributed by mohit kumar 29 // C# program for the// above approachusing System;class GFG{ // Function to find the maximum// sum not exceeding K possible// by selecting a subset of// non-adjacent elementspublic static int maxSum(int []a, int n, int k){ // Base Case if (n <= 0) return 0; // Not selecting current element int option = maxSum(a, n - 1, k); // If selecting current // element is possible if (k >= a[n - 1]) option = Math.Max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {50, 10, 20, 30, 40}; int N = arr.Length; // Given K int K = 100; // Function Call Console.WriteLine(maxSum(arr, N, K));}} // This code is contributed by Rajput-Ji <script> // Javascript program for the// above approach // Function to find the maximum sum// not exceeding K possible by selecting// a subset of non-adjacent elementsfunction maxSum(a, n, k){ // Base Case if (n <= 0) return 0; // Not selecting current element let option = maxSum(a, n - 1, k); // If selecting current element // is possible if (k >= a[n - 1]) option = Math.max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Code // Given array arr[]let arr = [ 50, 10, 20, 30, 40 ]; let N = arr.length; // Given Klet K = 100; // Function Calldocument.write(maxSum(arr, N, K)); // This code is contributed by target_2 </script> 90 Time Complexity: O(2N)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Two possible options exist for every array element: Either skip the current element and proceed to the next element.Select the current element only if it is smaller than or equal to K. Either skip the current element and proceed to the next element. Select the current element only if it is smaller than or equal to K. Follow the steps below to solve the problem: Initialize an array dp[N][K+1] with -1 where dp[i][j] will store the maximum sum to make sum j using elements up to index i.From the above transition, find the maximum sums if the current element gets picked and if it is not picked, recursively.Store the minimum answer for the current state.Also, add the base condition that if the current state (i, j) is already visited i.e., dp[i][j]!=-1 return dp[i][j].Print dp[N][K] as the maximum possible sum. Initialize an array dp[N][K+1] with -1 where dp[i][j] will store the maximum sum to make sum j using elements up to index i. From the above transition, find the maximum sums if the current element gets picked and if it is not picked, recursively. Store the minimum answer for the current state. Also, add the base condition that if the current state (i, j) is already visited i.e., dp[i][j]!=-1 return dp[i][j]. Print dp[N][K] as the maximum possible sum. 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; // Initialize dpint dp[1005][1005]; // Function find the maximum sum that// doesn't exceeds K by choosing elementsint maxSum(int* a, int n, int k){ // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element int option = maxSum(a, n - 1, k); // Pick the current element if (k >= a[n - 1]) option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return and store the result return dp[n][k] = option;} // Driver Codeint main(){ int N = 5; int arr[] = { 50, 10, 20, 30, 40 }; int K = 100; // Fill dp array with -1 memset(dp, -1, sizeof(dp)); // Print answer cout << maxSum(arr, N, K) << endl;} // This code is contributed by bolliranadheer // Java program for the above approach import java.util.*; class GFG { // Function find the maximum sum that // doesn't exceeds K by choosing elements public static int maxSum(int a[], int n, int k, int[][] dp) { // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element int option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the result return dp[n][k] = option; } // Driver Code public static void main(String[] args) { int arr[] = { 50, 10, 20, 30, 40 }; int N = arr.length; int K = 100; // Initialize dp int dp[][] = new int[N + 1][K + 1]; for (int i[] : dp) { Arrays.fill(i, -1); } // Print answer System.out.println(maxSum(arr, N, K, dp)); }} # Python3 program for the# above approach # Function find the maximum# sum that doesn't exceeds K# by choosing elementsdef maxSum(a, n, k, dp): # Base Case if (n <= 0): return 0; # Return the memoized state if (dp[n][k] != -1): return dp[n][k]; # Dont pick the current # element option = maxSum(a, n - 1, k, dp); # Pick the current element if (k >= a[n - 1]): option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); dp[n][k] = option; # Return and store # the result return dp[n][k]; # Driver Codeif __name__ == '__main__': arr = [50, 10, 20, 30, 40]; N = len(arr); K = 100; # Initialize dp dp = [[-1 for i in range(K + 1)] for j in range(N + 1)] # Print answer print(maxSum(arr, N, K, dp)); # This code is contributed by shikhasingrajput // C# program for the// above approachusing System;class GFG{ // Function find the maximum// sum that doesn't exceeds K// by choosing elementspublic static int maxSum(int []a, int n, int k, int[,] dp){ // Base Case if (n <= 0) return 0; // Return the memoized // state if (dp[n, k] != -1) return dp[n, k]; // Dont pick the current // element int option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.Max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the // result return dp[n, k] = option;} // Driver Codepublic static void Main(String[] args){ int []arr = {50, 10, 20, 30, 40}; int N = arr.Length; int K = 100; // Initialize dp int [,]dp = new int[N + 1, K + 1]; for (int j = 0; j < N + 1; j++) { for (int k = 0; k < K + 1; k++) dp[j, k] = -1; } // Print answer Console.WriteLine(maxSum(arr, N, K, dp));}} // This code is contributed by Rajput-Ji <script> // Javascript program to implement// the above approach // Function find the maximum sum that // doesn't exceeds K by choosing elements function maxSum(a, n, k, dp) { // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element let option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the result return dp[n][k] = option; } // Driver Code // Given array let arr = [ 50, 10, 20, 30, 40 ]; let N = arr.length; let K = 100; // Initialize dp let dp = new Array(N + 1); // Loop to create 2D array using 1D array for (var i = 0; i < 1000; i++) { dp[i] = new Array(2); } for (var i = 0; i < 1000; i++) { for (var j = 0; j < 1000; j++) { dp[i][j] = -1; } } // Print answer document.write(maxSum(arr, N, K, dp)); </script> 90 Time Complexity: O(N*K), where N is the size of the given array and K is the limit.Auxiliary Space: O(N) Rajput-Ji mohit kumar 29 GauravRajput1 shikhasingrajput bolliranadheer target_2 avijitmondal1998 Kirti_Mangal surinderdawra388 Arrays Combinatorial Dynamic Programming Hash Mathematical Recursion Arrays Hash Dynamic Programming Mathematical Recursion Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Jul, 2022" }, { "code": null, "e": 219, "s": 53, "text": "Given an array arr[] consisting of N integers and an integer K, the task is to select some non-adjacent array elements with the maximum possible sum not exceeding K." }, { "code": null, "e": 229, "s": 219, "text": "Examples:" }, { "code": null, "e": 410, "s": 229, "text": "Input: arr[] = {50, 10, 20, 30, 40}, K = 100Output: 90Explanation: To maximize the sum that doesn’t exceed K(= 100), select elements 50 and 40.Therefore, maximum possible sum = 90." }, { "code": null, "e": 595, "s": 410, "text": "Input: arr[] = {20, 10, 17, 12, 8, 9}, K = 64Output: 46Explanation: To maximize the sum that doesn’t exceed K(= 64), select elements 20, 17, and 9.Therefore, maximum possible sum = 46." }, { "code": null, "e": 917, "s": 595, "text": "Naive Approach: The simplest approach is to recursively generate all possible subsets of the given array and for each subset, check if it does not contain adjacent elements and has the sum not exceeding K. Among all subsets for which the above condition is found to be true, print the maximum sum obtained for any subset." }, { "code": null, "e": 968, "s": 917, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 972, "s": 968, "text": "C++" }, { "code": null, "e": 977, "s": 972, "text": "Java" }, { "code": null, "e": 985, "s": 977, "text": "Python3" }, { "code": null, "e": 988, "s": 985, "text": "C#" }, { "code": null, "e": 999, "s": 988, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximum sum not exceeding// K possible by selecting// a subset of non-adjacent elementsint maxSum(int a[], int n, int k){ // Base Case if (n <= 0) return 0; // Not selecting current // element int option = maxSum(a, n - 1, k); // If selecting current // element is possible if (k >= a[n - 1]) option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Codeint main(){ // Given array arr[] int arr[] = {50, 10, 20, 30, 40}; int N = sizeof(arr) / sizeof(arr[0]); // Given K int K = 100; // Function Call cout << (maxSum(arr, N, K));} // This code is contributed by gauravrajput1", "e": 1880, "s": 999, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { // Function to find the maximum sum // not exceeding K possible by selecting // a subset of non-adjacent elements public static int maxSum( int a[], int n, int k) { // Base Case if (n <= 0) return 0; // Not selecting current element int option = maxSum(a, n - 1, k); // If selecting current element // is possible if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option; } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = { 50, 10, 20, 30, 40 }; int N = arr.length; // Given K int K = 100; // Function Call System.out.println(maxSum(arr, N, K)); }}", "e": 2859, "s": 1880, "text": null }, { "code": "# Python3 program for the above approach # Function to find the maximum sum# not exceeding K possible by selecting# a subset of non-adjacent elementsdef maxSum(a, n, k): # Base Case if (n <= 0): return 0 # Not selecting current element option = maxSum(a, n - 1, k) # If selecting current element # is possible if (k >= a[n - 1]): option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])) # Return answer return option # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 50, 10, 20, 30, 40 ] N = len(arr) # Given K K = 100 # Function Call print(maxSum(arr, N, K)) # This code is contributed by mohit kumar 29", "e": 3574, "s": 2859, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function to find the maximum// sum not exceeding K possible// by selecting a subset of// non-adjacent elementspublic static int maxSum(int []a, int n, int k){ // Base Case if (n <= 0) return 0; // Not selecting current element int option = maxSum(a, n - 1, k); // If selecting current // element is possible if (k >= a[n - 1]) option = Math.Max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {50, 10, 20, 30, 40}; int N = arr.Length; // Given K int K = 100; // Function Call Console.WriteLine(maxSum(arr, N, K));}} // This code is contributed by Rajput-Ji", "e": 4423, "s": 3574, "text": null }, { "code": "<script> // Javascript program for the// above approach // Function to find the maximum sum// not exceeding K possible by selecting// a subset of non-adjacent elementsfunction maxSum(a, n, k){ // Base Case if (n <= 0) return 0; // Not selecting current element let option = maxSum(a, n - 1, k); // If selecting current element // is possible if (k >= a[n - 1]) option = Math.max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return answer return option;} // Driver Code // Given array arr[]let arr = [ 50, 10, 20, 30, 40 ]; let N = arr.length; // Given Klet K = 100; // Function Calldocument.write(maxSum(arr, N, K)); // This code is contributed by target_2 </script>", "e": 5162, "s": 4423, "text": null }, { "code": null, "e": 5165, "s": 5162, "text": "90" }, { "code": null, "e": 5209, "s": 5165, "text": "Time Complexity: O(2N)Auxiliary Space: O(N)" }, { "code": null, "e": 5353, "s": 5209, "text": "Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Two possible options exist for every array element:" }, { "code": null, "e": 5486, "s": 5353, "text": "Either skip the current element and proceed to the next element.Select the current element only if it is smaller than or equal to K." }, { "code": null, "e": 5551, "s": 5486, "text": "Either skip the current element and proceed to the next element." }, { "code": null, "e": 5620, "s": 5551, "text": "Select the current element only if it is smaller than or equal to K." }, { "code": null, "e": 5665, "s": 5620, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 6117, "s": 5665, "text": "Initialize an array dp[N][K+1] with -1 where dp[i][j] will store the maximum sum to make sum j using elements up to index i.From the above transition, find the maximum sums if the current element gets picked and if it is not picked, recursively.Store the minimum answer for the current state.Also, add the base condition that if the current state (i, j) is already visited i.e., dp[i][j]!=-1 return dp[i][j].Print dp[N][K] as the maximum possible sum." }, { "code": null, "e": 6242, "s": 6117, "text": "Initialize an array dp[N][K+1] with -1 where dp[i][j] will store the maximum sum to make sum j using elements up to index i." }, { "code": null, "e": 6364, "s": 6242, "text": "From the above transition, find the maximum sums if the current element gets picked and if it is not picked, recursively." }, { "code": null, "e": 6412, "s": 6364, "text": "Store the minimum answer for the current state." }, { "code": null, "e": 6529, "s": 6412, "text": "Also, add the base condition that if the current state (i, j) is already visited i.e., dp[i][j]!=-1 return dp[i][j]." }, { "code": null, "e": 6573, "s": 6529, "text": "Print dp[N][K] as the maximum possible sum." }, { "code": null, "e": 6624, "s": 6573, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 6628, "s": 6624, "text": "C++" }, { "code": null, "e": 6633, "s": 6628, "text": "Java" }, { "code": null, "e": 6641, "s": 6633, "text": "Python3" }, { "code": null, "e": 6644, "s": 6641, "text": "C#" }, { "code": null, "e": 6655, "s": 6644, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Initialize dpint dp[1005][1005]; // Function find the maximum sum that// doesn't exceeds K by choosing elementsint maxSum(int* a, int n, int k){ // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element int option = maxSum(a, n - 1, k); // Pick the current element if (k >= a[n - 1]) option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1])); // Return and store the result return dp[n][k] = option;} // Driver Codeint main(){ int N = 5; int arr[] = { 50, 10, 20, 30, 40 }; int K = 100; // Fill dp array with -1 memset(dp, -1, sizeof(dp)); // Print answer cout << maxSum(arr, N, K) << endl;} // This code is contributed by bolliranadheer", "e": 7593, "s": 6655, "text": null }, { "code": "// Java program for the above approach import java.util.*; class GFG { // Function find the maximum sum that // doesn't exceeds K by choosing elements public static int maxSum(int a[], int n, int k, int[][] dp) { // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element int option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the result return dp[n][k] = option; } // Driver Code public static void main(String[] args) { int arr[] = { 50, 10, 20, 30, 40 }; int N = arr.length; int K = 100; // Initialize dp int dp[][] = new int[N + 1][K + 1]; for (int i[] : dp) { Arrays.fill(i, -1); } // Print answer System.out.println(maxSum(arr, N, K, dp)); }}", "e": 8816, "s": 7593, "text": null }, { "code": "# Python3 program for the# above approach # Function find the maximum# sum that doesn't exceeds K# by choosing elementsdef maxSum(a, n, k, dp): # Base Case if (n <= 0): return 0; # Return the memoized state if (dp[n][k] != -1): return dp[n][k]; # Dont pick the current # element option = maxSum(a, n - 1, k, dp); # Pick the current element if (k >= a[n - 1]): option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); dp[n][k] = option; # Return and store # the result return dp[n][k]; # Driver Codeif __name__ == '__main__': arr = [50, 10, 20, 30, 40]; N = len(arr); K = 100; # Initialize dp dp = [[-1 for i in range(K + 1)] for j in range(N + 1)] # Print answer print(maxSum(arr, N, K, dp)); # This code is contributed by shikhasingrajput", "e": 9761, "s": 8816, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function find the maximum// sum that doesn't exceeds K// by choosing elementspublic static int maxSum(int []a, int n, int k, int[,] dp){ // Base Case if (n <= 0) return 0; // Return the memoized // state if (dp[n, k] != -1) return dp[n, k]; // Dont pick the current // element int option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.Max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the // result return dp[n, k] = option;} // Driver Codepublic static void Main(String[] args){ int []arr = {50, 10, 20, 30, 40}; int N = arr.Length; int K = 100; // Initialize dp int [,]dp = new int[N + 1, K + 1]; for (int j = 0; j < N + 1; j++) { for (int k = 0; k < K + 1; k++) dp[j, k] = -1; } // Print answer Console.WriteLine(maxSum(arr, N, K, dp));}} // This code is contributed by Rajput-Ji", "e": 10900, "s": 9761, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function find the maximum sum that // doesn't exceeds K by choosing elements function maxSum(a, n, k, dp) { // Base Case if (n <= 0) return 0; // Return the memoized state if (dp[n][k] != -1) return dp[n][k]; // Dont pick the current element let option = maxSum(a, n - 1, k, dp); // Pick the current element if (k >= a[n - 1]) option = Math.max( option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1], dp)); // Return and store the result return dp[n][k] = option; } // Driver Code // Given array let arr = [ 50, 10, 20, 30, 40 ]; let N = arr.length; let K = 100; // Initialize dp let dp = new Array(N + 1); // Loop to create 2D array using 1D array for (var i = 0; i < 1000; i++) { dp[i] = new Array(2); } for (var i = 0; i < 1000; i++) { for (var j = 0; j < 1000; j++) { dp[i][j] = -1; } } // Print answer document.write(maxSum(arr, N, K, dp)); </script>", "e": 12205, "s": 10900, "text": null }, { "code": null, "e": 12208, "s": 12205, "text": "90" }, { "code": null, "e": 12313, "s": 12208, "text": "Time Complexity: O(N*K), where N is the size of the given array and K is the limit.Auxiliary Space: O(N)" }, { "code": null, "e": 12323, "s": 12313, "text": "Rajput-Ji" }, { "code": null, "e": 12338, "s": 12323, "text": "mohit kumar 29" }, { "code": null, "e": 12352, "s": 12338, "text": "GauravRajput1" }, { "code": null, "e": 12369, "s": 12352, "text": "shikhasingrajput" }, { "code": null, "e": 12384, "s": 12369, "text": "bolliranadheer" }, { "code": null, "e": 12393, "s": 12384, "text": "target_2" }, { "code": null, "e": 12410, "s": 12393, "text": "avijitmondal1998" }, { "code": null, "e": 12423, "s": 12410, "text": "Kirti_Mangal" }, { "code": null, "e": 12440, "s": 12423, "text": "surinderdawra388" }, { "code": null, "e": 12447, "s": 12440, "text": "Arrays" }, { "code": null, "e": 12461, "s": 12447, "text": "Combinatorial" }, { "code": null, "e": 12481, "s": 12461, "text": "Dynamic Programming" }, { "code": null, "e": 12486, "s": 12481, "text": "Hash" }, { "code": null, "e": 12499, "s": 12486, "text": "Mathematical" }, { "code": null, "e": 12509, "s": 12499, "text": "Recursion" }, { "code": null, "e": 12516, "s": 12509, "text": "Arrays" }, { "code": null, "e": 12521, "s": 12516, "text": "Hash" }, { "code": null, "e": 12541, "s": 12521, "text": "Dynamic Programming" }, { "code": null, "e": 12554, "s": 12541, "text": "Mathematical" }, { "code": null, "e": 12564, "s": 12554, "text": "Recursion" }, { "code": null, "e": 12578, "s": 12564, "text": "Combinatorial" }, { "code": null, "e": 12676, "s": 12578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12708, "s": 12676, "text": "Introduction to Data Structures" }, { "code": null, "e": 12733, "s": 12708, "text": "Window Sliding Technique" }, { "code": null, "e": 12780, "s": 12733, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 12844, "s": 12780, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12875, "s": 12844, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 12935, "s": 12875, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 12973, "s": 12935, "text": "Permutation and Combination in Python" }, { "code": null, "e": 13001, "s": 12973, "text": "Factorial of a large number" }, { "code": null, "e": 13038, "s": 13001, "text": "Count of subsets with sum equal to X" } ]
Python MySQL – Join
13 Jun, 2022 A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. This is a MySQL Connector that allows Python to access MySQL Driver and implement SQL queries in its programming facility. Here we will try implementing Join clause on our Database and will study the output generated. Join allows you to combine two or more tables in SQL, based on related column between them. Based on this application of join there are three types of join: INNER JOIN gives the records that are produced by matching columns. JOIN and INNER JOIN both work the same. Syntax: SELECT column1, column2... FROM tablename JOIN tablename ON condition; SELECT column1, column2... FROM tablename INNER JOIN tablename ON condition; LEFT JOIN gives those records from table 1 removing exclusive contents of 2 Syntax: SELECT column1, column2... FROM tablename LEFT JOIN tablename ON condition; RIGHT JOIN gives all records from table 2 after removing exclusive records of 1. Syntax: SELECT column1, column2... FROM tablename RIGHT JOIN tablename ON condition; The following programs will help you understand this better. DATABASE IN USE: PROGRAM 1: Use of inner join Python3 import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.NAME from Student S JOIN \Student on S.Roll_no = Student.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x) OUTPUT: PROGRAM 2: use of LEFT JOIN Python3 import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.Name from STUDENT S\ LEFT JOIN Student s ON S.Roll_no = s.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x) OUTPUT: PROGRAM 3 : use of RIGHT JOIN Python3 import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement ="SELECT S.Name from STUDENT S RIGHT \JOIN Student s ON S.Roll_no = s.Roll_no" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x) OUTPUT: mitalibhola94 Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 314, "s": 52, "text": "A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server." }, { "code": null, "e": 532, "s": 314, "text": "This is a MySQL Connector that allows Python to access MySQL Driver and implement SQL queries in its programming facility. Here we will try implementing Join clause on our Database and will study the output generated." }, { "code": null, "e": 690, "s": 532, "text": "Join allows you to combine two or more tables in SQL, based on related column between them. Based on this application of join there are three types of join: " }, { "code": null, "e": 806, "s": 690, "text": "INNER JOIN gives the records that are produced by matching columns. JOIN and INNER JOIN both work the same. Syntax:" }, { "code": null, "e": 877, "s": 806, "text": "SELECT column1, column2...\nFROM tablename\nJOIN tablename ON condition;" }, { "code": null, "e": 954, "s": 877, "text": "SELECT column1, column2...\nFROM tablename\nINNER JOIN tablename ON condition;" }, { "code": null, "e": 1038, "s": 954, "text": "LEFT JOIN gives those records from table 1 removing exclusive contents of 2 Syntax:" }, { "code": null, "e": 1114, "s": 1038, "text": "SELECT column1, column2...\nFROM tablename\nLEFT JOIN tablename ON condition;" }, { "code": null, "e": 1203, "s": 1114, "text": "RIGHT JOIN gives all records from table 2 after removing exclusive records of 1. Syntax:" }, { "code": null, "e": 1280, "s": 1203, "text": "SELECT column1, column2...\nFROM tablename\nRIGHT JOIN tablename ON condition;" }, { "code": null, "e": 1390, "s": 1280, "text": "The following programs will help you understand this better. DATABASE IN USE: PROGRAM 1: Use of inner join " }, { "code": null, "e": 1398, "s": 1390, "text": "Python3" }, { "code": "import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement =\"SELECT S.NAME from Student S JOIN \\Student on S.Roll_no = Student.Roll_no\" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x)", "e": 1777, "s": 1398, "text": null }, { "code": null, "e": 1815, "s": 1777, "text": "OUTPUT: PROGRAM 2: use of LEFT JOIN " }, { "code": null, "e": 1823, "s": 1815, "text": "Python3" }, { "code": "import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement =\"SELECT S.Name from STUDENT S\\ LEFT JOIN Student s ON S.Roll_no = s.Roll_no\" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x)", "e": 2203, "s": 1823, "text": null }, { "code": null, "e": 2243, "s": 2203, "text": "OUTPUT: PROGRAM 3 : use of RIGHT JOIN " }, { "code": null, "e": 2251, "s": 2243, "text": "Python3" }, { "code": "import mysql.connector # Connecting to the databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # STUDENT and STudent are# two different databasestatement =\"SELECT S.Name from STUDENT S RIGHT \\JOIN Student s ON S.Roll_no = s.Roll_no\" cs.execute(statement)result_set = cs.fetchall() for x in result_set: print(x)", "e": 2632, "s": 2251, "text": null }, { "code": null, "e": 2641, "s": 2632, "text": "OUTPUT: " }, { "code": null, "e": 2655, "s": 2641, "text": "mitalibhola94" }, { "code": null, "e": 2668, "s": 2655, "text": "Python-mySQL" }, { "code": null, "e": 2675, "s": 2668, "text": "Python" }, { "code": null, "e": 2773, "s": 2675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2801, "s": 2773, "text": "Read JSON file using Python" }, { "code": null, "e": 2851, "s": 2801, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2873, "s": 2851, "text": "Python map() function" }, { "code": null, "e": 2917, "s": 2873, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2959, "s": 2917, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2981, "s": 2959, "text": "Enumerate() in Python" }, { "code": null, "e": 3016, "s": 2981, "text": "Read a file line by line in Python" }, { "code": null, "e": 3042, "s": 3016, "text": "Python String | replace()" }, { "code": null, "e": 3074, "s": 3042, "text": "How to Install PIP on Windows ?" } ]
Ruby | String count() Method
13 Dec, 2019 count is a String class method in Ruby. In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated. Syntax:str.count(parameter_list) Parameters: Here, str is the given string. Returns: The numbers of the characters. Example 1: # Ruby program to demonstrate # the count method # Taking a string and # using the methodstr = "String Counting"puts str.count "ing" Output: 7 Example 2: # Ruby program to demonstrate # the count method # Taking a string and # using the methodstr = "String Counting"puts str.count "^ing" str2 = "Ruby Method\\r\\n" puts str.count "\\" Output: 8 0 Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Dec, 2019" }, { "code": null, "e": 294, "s": 28, "text": "count is a String class method in Ruby. In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated." }, { "code": null, "e": 327, "s": 294, "text": "Syntax:str.count(parameter_list)" }, { "code": null, "e": 370, "s": 327, "text": "Parameters: Here, str is the given string." }, { "code": null, "e": 410, "s": 370, "text": "Returns: The numbers of the characters." }, { "code": null, "e": 421, "s": 410, "text": "Example 1:" }, { "code": "# Ruby program to demonstrate # the count method # Taking a string and # using the methodstr = \"String Counting\"puts str.count \"ing\"", "e": 561, "s": 421, "text": null }, { "code": null, "e": 569, "s": 561, "text": "Output:" }, { "code": null, "e": 572, "s": 569, "text": "7\n" }, { "code": null, "e": 583, "s": 572, "text": "Example 2:" }, { "code": "# Ruby program to demonstrate # the count method # Taking a string and # using the methodstr = \"String Counting\"puts str.count \"^ing\" str2 = \"Ruby Method\\\\r\\\\n\" puts str.count \"\\\\\"", "e": 773, "s": 583, "text": null }, { "code": null, "e": 781, "s": 773, "text": "Output:" }, { "code": null, "e": 786, "s": 781, "text": "8\n0\n" }, { "code": null, "e": 804, "s": 786, "text": "Ruby String-class" }, { "code": null, "e": 817, "s": 804, "text": "Ruby-Methods" }, { "code": null, "e": 822, "s": 817, "text": "Ruby" } ]
Deleting a Local GitHub Repository
04 Aug, 2021 When a user clones a Git repository from Github using the command git clone <url>, they get a copy of the remote repo on their local computer so that they can work on it on their current working directory where the repo got cloned without directly making changes on the remote repository. If you want to delete a local Github Repository that was cloned from to local computer without touching or making any changes to the Remote GitHub repository then follow the commands below: Step 1: Go into your project file cd <project_name> rm -rf <repository_folder>.git With the deletion of the ‘.git’ file, this will delete the .git file that contains a log of the commit history, its information, and also remote repository address from the working directory. We can think of this deletion as when we do git init to initialize the current working directory as Git directory, with the above command we are just reverting it back to not being a Git directory. Then what about the files and folder in the present working directory? This has to be deleted using the following set of command: Step 2: (Optional if you want to initialize working directory to another GitHub Repository See Additional steps below):- Go to the directory where the project is present (Note: Don’t go inside the project file). rm -rf <folder_name> What are rm and rf commands? In Linux, the user can delete/remove directories using rmdir or rm, in the above case we have made use of rm which is used to remove non-empty directories, unlike rmdir which is used to remove empty directories. This command is used to remove non-empty directories and all the files in the directory without being prompted if a directory or a file in the current working directory is write-protected (this case is very common when working on forked repository from GitHub) and the user is prompted to provide Y (for yes) to confirm the deletion of the write-protected file. Now using -rf with rm is effective as it can skip part of the user being prompted every time. Additional Steps: Suppose you want to initialize (git init) a new Github repository, and then add it to a new remote repository and then start adding and committing to the files being added from the current working directory. Make sure that the current working directory is the directory that needs to be pushed to the open-source platform (GitHub).git initgit remote add origin https://github.com/user/repo.gitgit push -u origin master Make sure that the current working directory is the directory that needs to be pushed to the open-source platform (GitHub). git init git remote add origin https://github.com/user/repo.git git push -u origin master Step 1: Navigate to your project https://github.com/your-github-username/Project-Name Step 2: Go to the settings option on the top right corner like the image above, and navigate down to the danger zone Step 3: Go and click on the delete this repository button and after which you will be prompted to make sure you are deleting and all these action will permanently affect the repository, in the box type your-username/project-name (replace it with yours). You may also be prompted to type in the GitHub password. Here we are going to delete a particular file from our github using Github. This feature can be useful when we have by ,mistake added few files in our project but we no longer need that. Deleting the File from GitHub Website Step 1: Navigate to your project https://github.com/your-github-username/Project-Name Step 2 : Browse to the file in your repository that you want to delete. At the top of the file, click on the Delete Icon. Step 3: At the bottom of the page, type a short, meaningful commit message that describes the change you made to the file Then it will show a alert like this that the File successfully deleted. annianni GitHub Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2021" }, { "code": null, "e": 317, "s": 28, "text": "When a user clones a Git repository from Github using the command git clone <url>, they get a copy of the remote repo on their local computer so that they can work on it on their current working directory where the repo got cloned without directly making changes on the remote repository." }, { "code": null, "e": 507, "s": 317, "text": "If you want to delete a local Github Repository that was cloned from to local computer without touching or making any changes to the Remote GitHub repository then follow the commands below:" }, { "code": null, "e": 541, "s": 507, "text": "Step 1: Go into your project file" }, { "code": null, "e": 559, "s": 541, "text": "cd <project_name>" }, { "code": null, "e": 591, "s": 559, "text": "rm -rf <repository_folder>.git " }, { "code": null, "e": 982, "s": 591, "text": "With the deletion of the ‘.git’ file, this will delete the .git file that contains a log of the commit history, its information, and also remote repository address from the working directory. We can think of this deletion as when we do git init to initialize the current working directory as Git directory, with the above command we are just reverting it back to not being a Git directory. " }, { "code": null, "e": 1053, "s": 982, "text": "Then what about the files and folder in the present working directory?" }, { "code": null, "e": 1112, "s": 1053, "text": "This has to be deleted using the following set of command:" }, { "code": null, "e": 1233, "s": 1112, "text": "Step 2: (Optional if you want to initialize working directory to another GitHub Repository See Additional steps below):-" }, { "code": null, "e": 1324, "s": 1233, "text": "Go to the directory where the project is present (Note: Don’t go inside the project file)." }, { "code": null, "e": 1345, "s": 1324, "text": "rm -rf <folder_name>" }, { "code": null, "e": 1374, "s": 1345, "text": "What are rm and rf commands?" }, { "code": null, "e": 1586, "s": 1374, "text": "In Linux, the user can delete/remove directories using rmdir or rm, in the above case we have made use of rm which is used to remove non-empty directories, unlike rmdir which is used to remove empty directories." }, { "code": null, "e": 2042, "s": 1586, "text": "This command is used to remove non-empty directories and all the files in the directory without being prompted if a directory or a file in the current working directory is write-protected (this case is very common when working on forked repository from GitHub) and the user is prompted to provide Y (for yes) to confirm the deletion of the write-protected file. Now using -rf with rm is effective as it can skip part of the user being prompted every time." }, { "code": null, "e": 2060, "s": 2042, "text": "Additional Steps:" }, { "code": null, "e": 2268, "s": 2060, "text": "Suppose you want to initialize (git init) a new Github repository, and then add it to a new remote repository and then start adding and committing to the files being added from the current working directory." }, { "code": null, "e": 2479, "s": 2268, "text": "Make sure that the current working directory is the directory that needs to be pushed to the open-source platform (GitHub).git initgit remote add origin https://github.com/user/repo.gitgit push -u origin master" }, { "code": null, "e": 2603, "s": 2479, "text": "Make sure that the current working directory is the directory that needs to be pushed to the open-source platform (GitHub)." }, { "code": null, "e": 2612, "s": 2603, "text": "git init" }, { "code": null, "e": 2667, "s": 2612, "text": "git remote add origin https://github.com/user/repo.git" }, { "code": null, "e": 2693, "s": 2667, "text": "git push -u origin master" }, { "code": null, "e": 2726, "s": 2693, "text": "Step 1: Navigate to your project" }, { "code": null, "e": 2779, "s": 2726, "text": "https://github.com/your-github-username/Project-Name" }, { "code": null, "e": 2897, "s": 2779, "text": "Step 2: Go to the settings option on the top right corner like the image above, and navigate down to the danger zone " }, { "code": null, "e": 3152, "s": 2897, "text": "Step 3: Go and click on the delete this repository button and after which you will be prompted to make sure you are deleting and all these action will permanently affect the repository, in the box type your-username/project-name (replace it with yours). " }, { "code": null, "e": 3209, "s": 3152, "text": "You may also be prompted to type in the GitHub password." }, { "code": null, "e": 3396, "s": 3209, "text": "Here we are going to delete a particular file from our github using Github. This feature can be useful when we have by ,mistake added few files in our project but we no longer need that." }, { "code": null, "e": 3434, "s": 3396, "text": "Deleting the File from GitHub Website" }, { "code": null, "e": 3467, "s": 3434, "text": "Step 1: Navigate to your project" }, { "code": null, "e": 3520, "s": 3467, "text": "https://github.com/your-github-username/Project-Name" }, { "code": null, "e": 3592, "s": 3520, "text": "Step 2 : Browse to the file in your repository that you want to delete." }, { "code": null, "e": 3642, "s": 3592, "text": "At the top of the file, click on the Delete Icon." }, { "code": null, "e": 3764, "s": 3642, "text": "Step 3: At the bottom of the page, type a short, meaningful commit message that describes the change you made to the file" }, { "code": null, "e": 3836, "s": 3764, "text": "Then it will show a alert like this that the File successfully deleted." }, { "code": null, "e": 3845, "s": 3836, "text": "annianni" }, { "code": null, "e": 3852, "s": 3845, "text": "GitHub" }, { "code": null, "e": 3856, "s": 3852, "text": "Git" } ]
Count number of digits after decimal on dividing a number
07 Jul, 2021 We are given two numbers A and B. We need to calculate the number of digits after decimal. If in case the numbers are irrational then print “INF”.Examples: Input : x = 5, y = 3 Output : INF 5/3 = 1.666.... Input : x = 3, y = 6 Output : 1 3/6 = 0.5 The idea is simple we follow school division and keep track of remainders while dividing one by one. If remainder becomes 0, we return count of digits seen after decimal. If remainder repeats, we return INF. C++ Java Python3 C# Javascript // CPP program to count digits after dot when a// number is divided by another.#include <bits/stdc++.h>using namespace std; int count(int x, int y){ int ans = 0; // Initialize result unordered_map<int, int> m; // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.find(x) != m.end()) return -1; m[x] = 1; x = x * 10; } return ans;} // Driver codeint main(){ int res = count(1, 2); (res == -1)? cout << "INF" : cout << res; cout << endl; res = count(5, 3); (res == -1)? cout << "INF" : cout << res; cout << endl; res = count(3, 5); (res == -1)? cout << "INF" : cout << res; return 0;} // Java program to count digits after dot when a// number is divided by another.import java.util.*; class GFG{ static int count(int x, int y){ int ans = 0; // Initialize result Map<Integer,Integer> m = new HashMap<>(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.containsKey(x)) return -1; m.put(x, 1); x = x * 10; } return ans;} // Driver codepublic static void main(String[] args){ int res = count(1, 2); if((res == -1)) System.out.println("INF"); else System.out.println(res); res = count(5, 3); if((res == -1)) System.out.println("INF"); else System.out.println(res); res = count(3, 5); if((res == -1)) System.out.println("INF"); else System.out.println(res);}} // This code is contributed by Rajput-Ji # Python3 program to count digits after dot# when a number is divided by another.def count(x, y): ans = 0 # Initialize result m = dict() # calculating remainder while x % y != 0: x %= y ans += 1 # if this remainder appeared before then # the numbers are irrational and would not # converge to a solution the digits after # decimal will be infinite if x in m: return -1 m[x] = 1 x *= 10 return ans # Driver Codeif __name__ == "__main__": res = count(1, 2) print("INF") if res == -1 else print(res) res = count(5, 3) print("INF") if res == -1 else print(res) res = count(3, 5) print("INF") if res == -1 else print(res) # This code is contributed by# sanjeev2552 // C# program to count digits after dot when a// number is divided by another.using System;using System.Collections.Generic; class GFG{ static int count(int x, int y){ int ans = 0; // Initialize result Dictionary<int,int> m = new Dictionary<int,int>(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.ContainsKey(x)) return -1; m.Add(x, 1); x = x * 10; } return ans;} // Driver codepublic static void Main(String[] args){ int res = count(1, 2); if((res == -1)) Console.WriteLine("INF"); else Console.WriteLine(res); res = count(5, 3); if((res == -1)) Console.WriteLine("INF"); else Console.WriteLine(res); res = count(3, 5); if((res == -1)) Console.WriteLine("INF"); else Console.WriteLine(res);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to count digits after dot when a// number is divided by another. function count(x,y){ let ans = 0; // Initialize result let m = new Map(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.has(x)) return -1; m.set(x, 1); x = x * 10; } return ans;} // Driver codelet res = count(1, 2); if((res == -1)) document.write("INF"+"<br>"); else document.write(res+"<br>"); res = count(5, 3); if((res == -1)) document.write("INF"+"<br>"); else document.write(res+"<br>"); res = count(3, 5); if((res == -1)) document.write("INF"+"<br>"); else document.write(res+"<br>"); // This code is contributed by rag2127 </script> Output: 1 INF 1 Time Complexity: O(N * log(N) ) Auxiliary Space: O(N) This article is contributed by Rahul Chawla. 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. Rajput-Ji 29AjayKumar sanjeev2552 ujjwalgoel1103 rag2127 cpp-unordered_map Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Find minimum number of coins that make a given value Program for Decimal to Binary Conversion
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2021" }, { "code": null, "e": 209, "s": 52, "text": "We are given two numbers A and B. We need to calculate the number of digits after decimal. If in case the numbers are irrational then print “INF”.Examples: " }, { "code": null, "e": 305, "s": 209, "text": "Input : x = 5, y = 3\nOutput : INF\n5/3 = 1.666....\n\nInput : x = 3, y = 6\nOutput : 1\n3/6 = 0.5 " }, { "code": null, "e": 515, "s": 305, "text": "The idea is simple we follow school division and keep track of remainders while dividing one by one. If remainder becomes 0, we return count of digits seen after decimal. If remainder repeats, we return INF. " }, { "code": null, "e": 519, "s": 515, "text": "C++" }, { "code": null, "e": 524, "s": 519, "text": "Java" }, { "code": null, "e": 532, "s": 524, "text": "Python3" }, { "code": null, "e": 535, "s": 532, "text": "C#" }, { "code": null, "e": 546, "s": 535, "text": "Javascript" }, { "code": "// CPP program to count digits after dot when a// number is divided by another.#include <bits/stdc++.h>using namespace std; int count(int x, int y){ int ans = 0; // Initialize result unordered_map<int, int> m; // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.find(x) != m.end()) return -1; m[x] = 1; x = x * 10; } return ans;} // Driver codeint main(){ int res = count(1, 2); (res == -1)? cout << \"INF\" : cout << res; cout << endl; res = count(5, 3); (res == -1)? cout << \"INF\" : cout << res; cout << endl; res = count(3, 5); (res == -1)? cout << \"INF\" : cout << res; return 0;}", "e": 1439, "s": 546, "text": null }, { "code": "// Java program to count digits after dot when a// number is divided by another.import java.util.*; class GFG{ static int count(int x, int y){ int ans = 0; // Initialize result Map<Integer,Integer> m = new HashMap<>(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.containsKey(x)) return -1; m.put(x, 1); x = x * 10; } return ans;} // Driver codepublic static void main(String[] args){ int res = count(1, 2); if((res == -1)) System.out.println(\"INF\"); else System.out.println(res); res = count(5, 3); if((res == -1)) System.out.println(\"INF\"); else System.out.println(res); res = count(3, 5); if((res == -1)) System.out.println(\"INF\"); else System.out.println(res);}} // This code is contributed by Rajput-Ji", "e": 2513, "s": 1439, "text": null }, { "code": "# Python3 program to count digits after dot# when a number is divided by another.def count(x, y): ans = 0 # Initialize result m = dict() # calculating remainder while x % y != 0: x %= y ans += 1 # if this remainder appeared before then # the numbers are irrational and would not # converge to a solution the digits after # decimal will be infinite if x in m: return -1 m[x] = 1 x *= 10 return ans # Driver Codeif __name__ == \"__main__\": res = count(1, 2) print(\"INF\") if res == -1 else print(res) res = count(5, 3) print(\"INF\") if res == -1 else print(res) res = count(3, 5) print(\"INF\") if res == -1 else print(res) # This code is contributed by# sanjeev2552", "e": 3289, "s": 2513, "text": null }, { "code": "// C# program to count digits after dot when a// number is divided by another.using System;using System.Collections.Generic; class GFG{ static int count(int x, int y){ int ans = 0; // Initialize result Dictionary<int,int> m = new Dictionary<int,int>(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.ContainsKey(x)) return -1; m.Add(x, 1); x = x * 10; } return ans;} // Driver codepublic static void Main(String[] args){ int res = count(1, 2); if((res == -1)) Console.WriteLine(\"INF\"); else Console.WriteLine(res); res = count(5, 3); if((res == -1)) Console.WriteLine(\"INF\"); else Console.WriteLine(res); res = count(3, 5); if((res == -1)) Console.WriteLine(\"INF\"); else Console.WriteLine(res);}} // This code is contributed by 29AjayKumar", "e": 4397, "s": 3289, "text": null }, { "code": "<script> // JavaScript program to count digits after dot when a// number is divided by another. function count(x,y){ let ans = 0; // Initialize result let m = new Map(); // calculating remainder while (x % y != 0) { x = x % y; ans++; // if this remainder appeared before then // the numbers are irrational and would not // converge to a solution the digits after // decimal will be infinite if (m.has(x)) return -1; m.set(x, 1); x = x * 10; } return ans;} // Driver codelet res = count(1, 2); if((res == -1)) document.write(\"INF\"+\"<br>\"); else document.write(res+\"<br>\"); res = count(5, 3); if((res == -1)) document.write(\"INF\"+\"<br>\"); else document.write(res+\"<br>\"); res = count(3, 5); if((res == -1)) document.write(\"INF\"+\"<br>\"); else document.write(res+\"<br>\"); // This code is contributed by rag2127 </script>", "e": 5392, "s": 4397, "text": null }, { "code": null, "e": 5401, "s": 5392, "text": "Output: " }, { "code": null, "e": 5409, "s": 5401, "text": "1\nINF\n1" }, { "code": null, "e": 5441, "s": 5409, "text": "Time Complexity: O(N * log(N) )" }, { "code": null, "e": 5463, "s": 5441, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 5884, "s": 5463, "text": "This article is contributed by Rahul Chawla. 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": 5894, "s": 5884, "text": "Rajput-Ji" }, { "code": null, "e": 5906, "s": 5894, "text": "29AjayKumar" }, { "code": null, "e": 5918, "s": 5906, "text": "sanjeev2552" }, { "code": null, "e": 5933, "s": 5918, "text": "ujjwalgoel1103" }, { "code": null, "e": 5941, "s": 5933, "text": "rag2127" }, { "code": null, "e": 5959, "s": 5941, "text": "cpp-unordered_map" }, { "code": null, "e": 5972, "s": 5959, "text": "Mathematical" }, { "code": null, "e": 5985, "s": 5972, "text": "Mathematical" }, { "code": null, "e": 6083, "s": 5985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6107, "s": 6083, "text": "Merge two sorted arrays" }, { "code": null, "e": 6128, "s": 6107, "text": "Operators in C / C++" }, { "code": null, "e": 6150, "s": 6128, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6164, "s": 6150, "text": "Prime Numbers" }, { "code": null, "e": 6206, "s": 6164, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6243, "s": 6206, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6286, "s": 6243, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 6318, "s": 6286, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6371, "s": 6318, "text": "Find minimum number of coins that make a given value" } ]
ZonedDateTime withZoneSameInstant() method in Java with Examples
23 Mar, 2022 The withZoneSameInstant() method of a ZonedDateTime class is used to return a copy of this ZonedDateTime object by changing the time-zone and without the instant. This method is based on retaining the same instant, thus gaps and overlaps in the local timeline have no effect on the result. Syntax: public ZonedDateTime withZoneSameInstant(ZoneId zone) Parameters: This method accepts one single parameter zone the time-zone to change to. It should not be null. Return value: This method returns a ZonedDateTime based on this date-time with the requested zone. Exception Thrown: DateTimeException if the result exceeds the supported date range. Example 1: Java // Java program to demonstrate// ZonedDateTime.withZoneSameInstant() method // Importing required classesimport java.time.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime.parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // Printing ZonedDateTime of Calcutta on console System.out.println("ZonedDateTime of Calcutta: " + zonedDT); // Applying withZoneSameInstant() ZonedDateTime zonedDT2 = zonedDT.withZoneSameInstant( ZoneId.of("Pacific/Fiji")); // Now printing ZonedDateTime of Fuji // after withZoneSameInstant() System.out.println("ZonedDateTime of Fuji: " + zonedDT2); }} ZonedDateTime of Calcutta: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta] ZonedDateTime of Fuji: 2018-12-07T02:51:12.123+13:00[Pacific/Fiji] Example 2: Java // Java program to Demonstrate// ZonedDateTime.withZoneSameInstant() method // Importing required classesimport java.time.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a ZonedDateTime object and // passing date and time of Europe/Paris ZonedDateTime zonedDT = ZonedDateTime.parse( "2018-10-25T23:12:31.123+02:00[Europe/Paris]"); // Printing ZonedDateTime of Paris on console // before applying withZoneSameInstant() method System.out.println("ZonedDateTime of Paris: " + zonedDT); // Now applying withZoneSameInstant() method ZonedDateTime zonedDT2 = zonedDT.withZoneSameInstant( ZoneId.of("Canada/Yukon")); // Printing ZonedDateTime // after applying withZoneSameInstant() System.out.println("ZonedDateTime of Yukon: " + zonedDT2); }} ZonedDateTime of Paris: 2018-10-25T23:12:31.123+02:00[Europe/Paris] ZonedDateTime of Yukon: 2018-10-25T14:12:31.123-07:00[Canada/Yukon] solankimayank sagartomar9927 Java-Functions Java-time package Java-ZonedDateTime Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 318, "s": 28, "text": "The withZoneSameInstant() method of a ZonedDateTime class is used to return a copy of this ZonedDateTime object by changing the time-zone and without the instant. This method is based on retaining the same instant, thus gaps and overlaps in the local timeline have no effect on the result." }, { "code": null, "e": 326, "s": 318, "text": "Syntax:" }, { "code": null, "e": 380, "s": 326, "text": "public ZonedDateTime withZoneSameInstant(ZoneId zone)" }, { "code": null, "e": 489, "s": 380, "text": "Parameters: This method accepts one single parameter zone the time-zone to change to. It should not be null." }, { "code": null, "e": 588, "s": 489, "text": "Return value: This method returns a ZonedDateTime based on this date-time with the requested zone." }, { "code": null, "e": 672, "s": 588, "text": "Exception Thrown: DateTimeException if the result exceeds the supported date range." }, { "code": null, "e": 683, "s": 672, "text": "Example 1:" }, { "code": null, "e": 688, "s": 683, "text": "Java" }, { "code": "// Java program to demonstrate// ZonedDateTime.withZoneSameInstant() method // Importing required classesimport java.time.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a ZonedDateTime object ZonedDateTime zonedDT = ZonedDateTime.parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // Printing ZonedDateTime of Calcutta on console System.out.println(\"ZonedDateTime of Calcutta: \" + zonedDT); // Applying withZoneSameInstant() ZonedDateTime zonedDT2 = zonedDT.withZoneSameInstant( ZoneId.of(\"Pacific/Fiji\")); // Now printing ZonedDateTime of Fuji // after withZoneSameInstant() System.out.println(\"ZonedDateTime of Fuji: \" + zonedDT2); }}", "e": 1561, "s": 688, "text": null }, { "code": null, "e": 1700, "s": 1561, "text": "ZonedDateTime of Calcutta: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\nZonedDateTime of Fuji: 2018-12-07T02:51:12.123+13:00[Pacific/Fiji]" }, { "code": null, "e": 1713, "s": 1702, "text": "Example 2:" }, { "code": null, "e": 1718, "s": 1713, "text": "Java" }, { "code": "// Java program to Demonstrate// ZonedDateTime.withZoneSameInstant() method // Importing required classesimport java.time.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a ZonedDateTime object and // passing date and time of Europe/Paris ZonedDateTime zonedDT = ZonedDateTime.parse( \"2018-10-25T23:12:31.123+02:00[Europe/Paris]\"); // Printing ZonedDateTime of Paris on console // before applying withZoneSameInstant() method System.out.println(\"ZonedDateTime of Paris: \" + zonedDT); // Now applying withZoneSameInstant() method ZonedDateTime zonedDT2 = zonedDT.withZoneSameInstant( ZoneId.of(\"Canada/Yukon\")); // Printing ZonedDateTime // after applying withZoneSameInstant() System.out.println(\"ZonedDateTime of Yukon: \" + zonedDT2); }}", "e": 2700, "s": 1718, "text": null }, { "code": null, "e": 2836, "s": 2700, "text": "ZonedDateTime of Paris: 2018-10-25T23:12:31.123+02:00[Europe/Paris]\nZonedDateTime of Yukon: 2018-10-25T14:12:31.123-07:00[Canada/Yukon]" }, { "code": null, "e": 2850, "s": 2836, "text": "solankimayank" }, { "code": null, "e": 2865, "s": 2850, "text": "sagartomar9927" }, { "code": null, "e": 2880, "s": 2865, "text": "Java-Functions" }, { "code": null, "e": 2898, "s": 2880, "text": "Java-time package" }, { "code": null, "e": 2917, "s": 2898, "text": "Java-ZonedDateTime" }, { "code": null, "e": 2922, "s": 2917, "text": "Java" }, { "code": null, "e": 2927, "s": 2922, "text": "Java" }, { "code": null, "e": 3025, "s": 2927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3056, "s": 3025, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3075, "s": 3056, "text": "Interfaces in Java" }, { "code": null, "e": 3105, "s": 3075, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3123, "s": 3105, "text": "ArrayList in Java" }, { "code": null, "e": 3138, "s": 3123, "text": "Stream In Java" }, { "code": null, "e": 3158, "s": 3138, "text": "Collections in Java" }, { "code": null, "e": 3190, "s": 3158, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3214, "s": 3190, "text": "Singleton Class in Java" }, { "code": null, "e": 3226, "s": 3214, "text": "Set in Java" } ]
Fabric.js Image Width Property - GeeksforGeeks
25 Jan, 2021 Fabric.js is a JavaScript library that is used to work with canvas. The canvas image is one of the class of fabric.js that is used to create image instances. The canvas image means the Image is movable and can be stretched according to requirement. The width property of the image is used to set the width of the image. Approach: First import the fabric.js library. After importing the library, create a canvas block in the body tag which will contain the image. After this, initialize an instance of Canvas and image class provided by Fabric.JS and use the width property to set the height of the canvas image. After this render the image on the canvas. Syntax: fabric.Image(image, { width: Number }); Parameters: This function takes a single parameter as mentioned above and described below: Width: This parameter takes a number to set the width of the canvas image. Example: This example uses FabricJS to set the width of the canvas image as shown in the below example: HTML <!DOCTYPE html> <html> <head> <!-- Adding the FabricJS library --> <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script> </head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Fabric.js | Image visible Property </b> <canvas id="canvas" width="400" height="300" style="border:2px solid #000000"> </canvas> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" width="100" height="100" id="my-image" style="display: none;"> <br> <button onclick="wid()">Clickme</button> <script> // Creating the instance of canvas object var canvas = new fabric.Canvas("canvas"); // Getting the image var img = document.getElementById('my-image'); // Creating the image instance var imgInstance = new fabric.Image(img, { }); function wid() { imgInstance = new fabric.Image(img, { width: 250 }); canvas.clear(); // Rendering the image to canvas canvas.add(imgInstance); canvas.centerObject(imgInstance); } canvas.add(imgInstance); canvas.centerObject(imgInstance); </script> </body> </html> Output: Before clicking the Button: After Clicking the Button: Fabric.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24935, "s": 24907, "text": "\n25 Jan, 2021" }, { "code": null, "e": 25255, "s": 24935, "text": "Fabric.js is a JavaScript library that is used to work with canvas. The canvas image is one of the class of fabric.js that is used to create image instances. The canvas image means the Image is movable and can be stretched according to requirement. The width property of the image is used to set the width of the image." }, { "code": null, "e": 25590, "s": 25255, "text": "Approach: First import the fabric.js library. After importing the library, create a canvas block in the body tag which will contain the image. After this, initialize an instance of Canvas and image class provided by Fabric.JS and use the width property to set the height of the canvas image. After this render the image on the canvas." }, { "code": null, "e": 25598, "s": 25590, "text": "Syntax:" }, { "code": null, "e": 25642, "s": 25598, "text": "fabric.Image(image, {\n width: Number\n});" }, { "code": null, "e": 25733, "s": 25642, "text": "Parameters: This function takes a single parameter as mentioned above and described below:" }, { "code": null, "e": 25808, "s": 25733, "text": "Width: This parameter takes a number to set the width of the canvas image." }, { "code": null, "e": 25912, "s": 25808, "text": "Example: This example uses FabricJS to set the width of the canvas image as shown in the below example:" }, { "code": null, "e": 25917, "s": 25912, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <!-- Adding the FabricJS library --> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script> </head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Fabric.js | Image visible Property </b> <canvas id=\"canvas\" width=\"400\" height=\"300\" style=\"border:2px solid #000000\"> </canvas> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png\" width=\"100\" height=\"100\" id=\"my-image\" style=\"display: none;\"> <br> <button onclick=\"wid()\">Clickme</button> <script> // Creating the instance of canvas object var canvas = new fabric.Canvas(\"canvas\"); // Getting the image var img = document.getElementById('my-image'); // Creating the image instance var imgInstance = new fabric.Image(img, { }); function wid() { imgInstance = new fabric.Image(img, { width: 250 }); canvas.clear(); // Rendering the image to canvas canvas.add(imgInstance); canvas.centerObject(imgInstance); } canvas.add(imgInstance); canvas.centerObject(imgInstance); </script> </body> </html>", "e": 27276, "s": 25917, "text": null }, { "code": null, "e": 27284, "s": 27276, "text": "Output:" }, { "code": null, "e": 27312, "s": 27284, "text": "Before clicking the Button:" }, { "code": null, "e": 27339, "s": 27312, "text": "After Clicking the Button:" }, { "code": null, "e": 27349, "s": 27339, "text": "Fabric.js" }, { "code": null, "e": 27360, "s": 27349, "text": "JavaScript" }, { "code": null, "e": 27377, "s": 27360, "text": "Web Technologies" }, { "code": null, "e": 27475, "s": 27377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27484, "s": 27475, "text": "Comments" }, { "code": null, "e": 27497, "s": 27484, "text": "Old Comments" }, { "code": null, "e": 27558, "s": 27497, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27599, "s": 27558, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27653, "s": 27599, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27693, "s": 27653, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27755, "s": 27693, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27811, "s": 27755, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27844, "s": 27811, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27906, "s": 27844, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27949, "s": 27906, "text": "How to fetch data from an API in ReactJS ?" } ]
Transform the array | Practice | GeeksforGeeks
Given an array arr[] of size N containing integers, zero is considered an invalid number, and rest all other numbers are valid. If two nearest valid numbers are equal then double the value of the first one and make the second number as 0. At last move all the valid numbers on the left. Example 1: Input: N = 12 arr[] = {2, 4, 5, 0, 0, 5, 4, 8, 6, 0, 6, 8} Output: 2 4 10 4 8 12 8 0 0 0 0 0 Explanation: After performing above given operation we get array as, 2 4 10 0 0 0 4 8 12 0 0 8, then shifting all zero's to the right, we get resultant array as - 2 4 10 4 8 12 8 0 0 0 0 0 Example 2: Input: N = 2, arr[] = {0, 0} Output: 0 0 Explanation: All elements in the array are invalid . Your Task: You don't need to read input or print anything. Complete the function valid() that takes array arr[] and integer N as input parameters and returns the resultant array. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 0 chessnoobdj4 months ago C++ vector<int> valid(int arr[],int n) { int i = 0; while(i < n-1){ if(arr[i] && arr[i] == arr[i+1]){ arr[i] *= 2; arr[i+1] = 0; int j = i+1; while(j<n && !arr[j]) j += 1; if(j<n) swap(arr[i+1], arr[j]); } else if(arr[i] && !arr[i+1]){ int j = i+1; while(j<n && !arr[j]) j += 1; if(arr[i] == arr[j]){ arr[i] *= 2; arr[j] = 0; } while(j<n && !arr[j]) j += 1; if(j<n) swap(arr[i+1], arr[j]); } i += 1; if(i>0 && arr[i] && arr[i] == arr[i-1]) i -= 1; } int idx = 0; vector <int> res(n, 0); for(int i=0; i<n; i++){ if(arr[i]) res[idx++] = arr[i]; } return res; } vector<int> valid(int arr[],int n) { int i,j=0,prev=0,c=0; for(i=0;i<n;i++){ if(arr[i]>0){ if(arr[i]==prev) { arr[i] *= 2; prev=arr[i]; swap(arr[i], arr[j]); arr[i]=0; c++; } else{ prev=arr[i]; j=i; } } } int idx = 0; vector <int> res(n, 0); for(int i=0; i<n; i++){ if(arr[i]) res[idx++] = arr[i]; } return res; } 0 poojayadav1004184 months ago void move(int a[],int s){ int i=0; for(int j=0;j<s;j++){ if(a[j]!=0){ swap(a[i],a[j]); i++; } }}vector<int> valid(int arr[],int n){ move(arr,n); for(int i=0;i<n;i++){ if(arr[i]==arr[i+1] && arr[i+1]!=0){ arr[i+1]=0; arr[i]=2*arr[i]; } } move(arr,n); return arr;} what is the problem in this? 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": 513, "s": 226, "text": "Given an array arr[] of size N containing integers, zero is considered an invalid number, and rest all other numbers are valid. If two nearest valid numbers are equal then double the value of the first one and make the second number as 0. At last move all the valid numbers on the left." }, { "code": null, "e": 524, "s": 513, "text": "Example 1:" }, { "code": null, "e": 843, "s": 524, "text": "Input: N = 12\narr[] = {2, 4, 5, 0, 0, 5, 4, 8, 6, 0, \n 6, 8}\nOutput: 2 4 10 4 8 12 8 0 0 0 0 0\nExplanation: After performing above \ngiven operation we get array as,\n2 4 10 0 0 0 4 8 12 0 0 8, then shifting\nall zero's to the right, we get resultant\narray as - 2 4 10 4 8 12 8 0 0 0 0 0 " }, { "code": null, "e": 855, "s": 843, "text": "\nExample 2:" }, { "code": null, "e": 950, "s": 855, "text": "Input: N = 2, arr[] = {0, 0}\nOutput: 0 0\nExplanation: All elements in the array \nare invalid ." }, { "code": null, "e": 1131, "s": 952, "text": "Your Task:\nYou don't need to read input or print anything. Complete the function valid() that takes array arr[] and integer N as input parameters and returns the resultant array." }, { "code": null, "e": 1195, "s": 1133, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1222, "s": 1197, "text": "Constraints:\n1 ≤ N ≤ 105" }, { "code": null, "e": 1226, "s": 1224, "text": "0" }, { "code": null, "e": 1250, "s": 1226, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 1254, "s": 1250, "text": "C++" }, { "code": null, "e": 2205, "s": 1254, "text": "vector<int> valid(int arr[],int n)\n\t{\n\t int i = 0;\n\t while(i < n-1){\n\t if(arr[i] && arr[i] == arr[i+1]){\n\t arr[i] *= 2;\n\t arr[i+1] = 0;\n\t int j = i+1;\n\t while(j<n && !arr[j])\n\t j += 1;\n\t if(j<n)\n\t swap(arr[i+1], arr[j]); \n\t }\n\t else if(arr[i] && !arr[i+1]){\n\t int j = i+1;\n\t while(j<n && !arr[j])\n\t j += 1;\n\t if(arr[i] == arr[j]){\n\t arr[i] *= 2;\n\t arr[j] = 0;\n\t }\n\t while(j<n && !arr[j])\n\t j += 1;\n\t if(j<n)\n\t swap(arr[i+1], arr[j]);\n\t }\n\t i += 1;\n\t if(i>0 && arr[i] && arr[i] == arr[i-1])\n\t i -= 1;\n\t }\n\t int idx = 0;\n\t vector <int> res(n, 0);\n\t for(int i=0; i<n; i++){\n\t if(arr[i])\n\t res[idx++] = arr[i];\n\t }\n\t return res;\n\t}" }, { "code": null, "e": 2760, "s": 2205, "text": "vector<int> valid(int arr[],int n)\n\t{\n\t int i,j=0,prev=0,c=0;\n\t for(i=0;i<n;i++){\n\t if(arr[i]>0){\n\t if(arr[i]==prev) {\n\t arr[i] *= 2;\n\t prev=arr[i];\n\t swap(arr[i], arr[j]);\n\t arr[i]=0;\n\t c++;\n\t }\n\t else{\n\t prev=arr[i];\n\t j=i;\n\t }\n\t }\n\t }\n\t int idx = 0;\n\t vector <int> res(n, 0);\n\t for(int i=0; i<n; i++){\n\t if(arr[i])\n\t res[idx++] = arr[i];\n\t }\n\t return res;\n\t}" }, { "code": null, "e": 2762, "s": 2760, "text": "0" }, { "code": null, "e": 2791, "s": 2762, "text": "poojayadav1004184 months ago" }, { "code": null, "e": 3147, "s": 2791, "text": "void move(int a[],int s){ int i=0; for(int j=0;j<s;j++){ if(a[j]!=0){ swap(a[i],a[j]); i++; } }}vector<int> valid(int arr[],int n){ move(arr,n); for(int i=0;i<n;i++){ if(arr[i]==arr[i+1] && arr[i+1]!=0){ arr[i+1]=0; arr[i]=2*arr[i]; } } move(arr,n); return arr;}" }, { "code": null, "e": 3176, "s": 3147, "text": "what is the problem in this?" }, { "code": null, "e": 3322, "s": 3176, "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": 3358, "s": 3322, "text": " Login to access your submissions. " }, { "code": null, "e": 3368, "s": 3358, "text": "\nProblem\n" }, { "code": null, "e": 3378, "s": 3368, "text": "\nContest\n" }, { "code": null, "e": 3441, "s": 3378, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3589, "s": 3441, "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": 3797, "s": 3589, "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": 3903, "s": 3797, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
maximize_window driver method – Selenium Python
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around maximize_window driver method in Selenium. maximize_window method maximizes the current window that webdriver is using. Syntax – driver.maximize_window() Example –Now one can use maximize_window method as a driver method as below – diver.get("https://www.geeksforgeeks.org/") driver.maximize_window() To demonstrate, maximize_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s maximize window, Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # maximize window positiondriver.maximize_window() Output –Screenshot added – 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 767, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc." }, { "code": null, "e": 916, "s": 767, "text": "This article revolves around maximize_window driver method in Selenium. maximize_window method maximizes the current window that webdriver is using." }, { "code": null, "e": 925, "s": 916, "text": "Syntax –" }, { "code": null, "e": 950, "s": 925, "text": "driver.maximize_window()" }, { "code": null, "e": 1028, "s": 950, "text": "Example –Now one can use maximize_window method as a driver method as below –" }, { "code": null, "e": 1098, "s": 1028, "text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.maximize_window()\n" }, { "code": null, "e": 1267, "s": 1098, "text": "To demonstrate, maximize_window method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s maximize window," }, { "code": null, "e": 1277, "s": 1267, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # maximize window positiondriver.maximize_window()", "e": 1504, "s": 1277, "text": null }, { "code": null, "e": 1531, "s": 1504, "text": "Output –Screenshot added –" }, { "code": null, "e": 1547, "s": 1531, "text": "Python-selenium" }, { "code": null, "e": 1556, "s": 1547, "text": "selenium" }, { "code": null, "e": 1563, "s": 1556, "text": "Python" }, { "code": null, "e": 1661, "s": 1563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1693, "s": 1661, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1720, "s": 1693, "text": "Python Classes and Objects" }, { "code": null, "e": 1741, "s": 1720, "text": "Python OOPs Concepts" }, { "code": null, "e": 1764, "s": 1741, "text": "Introduction To PYTHON" }, { "code": null, "e": 1820, "s": 1764, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1862, "s": 1820, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1893, "s": 1862, "text": "Python | os.path.join() method" }, { "code": null, "e": 1935, "s": 1893, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1974, "s": 1935, "text": "Python | Get unique values from a list" } ]
How to convert special characters to HTML in Javascript?
27 Sep, 2019 In HTML there are many cases in which the browser gets confused while rendering the page. In HTML the less-than sign ( < ) means the opening of some tag and if we place an element an after it like ‘a’ or ‘h’ then browser identifies them as an anchor and heading tab respectively. Similar is the case with some special character including less than, at the rate (@), front and backslash, etc. Example of Problem: This example is an illustration of the problem caused when the HTML text is not converted to the special format. <html> <head> </head> <body> <div> If b<a and a<h then b<h. <!-- the browser understands it as anchor tag--> </div> </body></html> The part b<a is problematic. The browser understands it as anchor tags. Similar is the case with b<hOutput: If b Solution 1: One way to solve it is to manually by putting special symbols in the pace of the respective special character which is problematic. But for very heavy websites it is very difficult to draw all the characters and then render it in HTML. <html> <head></head> <body> <div> If b < a and ab < h then b < h. <!-- the browser understands it as less than--> </div></body> </html> Output: If b < a and ab < h then b < h. JavaScript based Solution One another way is to convert each special character to its respective HTML code using javascript. Within the script we will replace all the special charters with the help of a regular expression which is “&#” + ASCII value of character + “;”. We apply the same rule with all the text on the page. <html> <head> <script> function Encode(string) { var i = string.length, a = []; while (i--) { var iC = string[i].charCodeAt(); if (iC < 65 || iC > 127 || (iC > 90 && iC < 97)) { a[i] = '&#' + iC + ';'; } else { a[i] = string[i]; } } return a.join(''); } </script></head> <body> <script> document.write(Encode("If b<a and a<h then b<h")); </script></body> </html> Output: If b<a and a<h then b<h Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 420, "s": 28, "text": "In HTML there are many cases in which the browser gets confused while rendering the page. In HTML the less-than sign ( < ) means the opening of some tag and if we place an element an after it like ‘a’ or ‘h’ then browser identifies them as an anchor and heading tab respectively. Similar is the case with some special character including less than, at the rate (@), front and backslash, etc." }, { "code": null, "e": 553, "s": 420, "text": "Example of Problem: This example is an illustration of the problem caused when the HTML text is not converted to the special format." }, { "code": "<html> <head> </head> <body> <div> If b<a and a<h then b<h. <!-- the browser understands it as anchor tag--> </div> </body></html>", "e": 717, "s": 553, "text": null }, { "code": null, "e": 825, "s": 717, "text": "The part b<a is problematic. The browser understands it as anchor tags. Similar is the case with b<hOutput:" }, { "code": null, "e": 830, "s": 825, "text": "If b" }, { "code": null, "e": 1078, "s": 830, "text": "Solution 1: One way to solve it is to manually by putting special symbols in the pace of the respective special character which is problematic. But for very heavy websites it is very difficult to draw all the characters and then render it in HTML." }, { "code": "<html> <head></head> <body> <div> If b < a and ab < h then b < h. <!-- the browser understands it as less than--> </div></body> </html>", "e": 1243, "s": 1078, "text": null }, { "code": null, "e": 1251, "s": 1243, "text": "Output:" }, { "code": null, "e": 1283, "s": 1251, "text": "If b < a and ab < h then b < h." }, { "code": null, "e": 1607, "s": 1283, "text": "JavaScript based Solution One another way is to convert each special character to its respective HTML code using javascript. Within the script we will replace all the special charters with the help of a regular expression which is “&#” + ASCII value of character + “;”. We apply the same rule with all the text on the page." }, { "code": "<html> <head> <script> function Encode(string) { var i = string.length, a = []; while (i--) { var iC = string[i].charCodeAt(); if (iC < 65 || iC > 127 || (iC > 90 && iC < 97)) { a[i] = '&#' + iC + ';'; } else { a[i] = string[i]; } } return a.join(''); } </script></head> <body> <script> document.write(Encode(\"If b<a and a<h then b<h\")); </script></body> </html>", "e": 2165, "s": 1607, "text": null }, { "code": null, "e": 2173, "s": 2165, "text": "Output:" }, { "code": null, "e": 2197, "s": 2173, "text": "If b<a and a<h then b<h" }, { "code": null, "e": 2204, "s": 2197, "text": "Picked" }, { "code": null, "e": 2215, "s": 2204, "text": "JavaScript" }, { "code": null, "e": 2232, "s": 2215, "text": "Web Technologies" }, { "code": null, "e": 2259, "s": 2232, "text": "Web technologies Questions" }, { "code": null, "e": 2357, "s": 2259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2418, "s": 2357, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2490, "s": 2418, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2530, "s": 2490, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2572, "s": 2530, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2613, "s": 2572, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2646, "s": 2613, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2708, "s": 2646, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2769, "s": 2708, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2819, "s": 2769, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Basics of File Handling in C
Here we will see some basic file handling operations in C. The operations are listed below: Writing into a File Reading from File Appending in a File See the code to get the idea how we write into a file #include <stdio.h> int main() { FILE *fp; char *filename = "sample.txt"; char *content = "Hey there! You've successfully created a file with content in c programming language."; /* open for writing */ fp = fopen(filename, "w"); if( fp == NULL ) { printf("%s: failed to open. \n", filename); return -1; } else { printf("%s: opened in write mode.\n", filename); } /* Write content to file */ fprintf(fp, "%s\n", content); if( !fclose(fp) ) printf("%s: closed successfully.\n", filename); return 0; } sample.txt: opened in write mode. sample.txt: closed successfully. Se the code to get the idea how we read from a file Make a file (file_read.txt): You have opened a file using C programming language, in read-only mode. #include <stdio.h> int main() { FILE *fp; char *filename = "file_read.txt"; char ch; /* open for writing */ fp = fopen(filename, "r"); if (fp == NULL) { printf("%s does not exists \n", filename); return; } else { printf("%s: opened in read mode.\n\n", filename); } while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } if (!fclose(fp)) printf("\n%s: closed.\n", filename); return 0; } file_read.txt: opened in read mode. You have opened a file using C programming language, in read-only mode. file_read.txt: closed. Se the code to get the idea how we can append lines into a file. This text was already there in the file. #include <stdio.h> int main() { FILE *fp; char ch; char *filename = "file_append.txt"; char *content = "This text is appeneded later to the file, using C programming."; /* open for writing */ fp = fopen(filename, "r"); printf("\nContents of %s -\n\n", filename); while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } fclose(fp); fp = fopen(filename, "a"); /* Write content to file */ fprintf(fp, "%s\n", content); fclose(fp); fp = fopen(filename, "r"); printf("\nContents of %s -\n", filename); while ((ch = fgetc(fp) )!= EOF) { printf ("%c", ch); } fclose(fp); return 0; } Contents of file_append.txt - This text was already there in the file. Appending content to file_append.txt... Content of file_append.txt after 'append' operation is - This text was already there in the file. This text is appeneded later to the file, using C programming.
[ { "code": null, "e": 1154, "s": 1062, "text": "Here we will see some basic file handling operations in C. The operations are listed below:" }, { "code": null, "e": 1174, "s": 1154, "text": "Writing into a File" }, { "code": null, "e": 1192, "s": 1174, "text": "Reading from File" }, { "code": null, "e": 1212, "s": 1192, "text": "Appending in a File" }, { "code": null, "e": 1266, "s": 1212, "text": "See the code to get the idea how we write into a file" }, { "code": null, "e": 1824, "s": 1266, "text": "#include <stdio.h>\nint main() {\n FILE *fp;\n char *filename = \"sample.txt\";\n char *content = \"Hey there! You've successfully created a file with content in c programming language.\";\n /* open for writing */\n fp = fopen(filename, \"w\");\n if( fp == NULL ) {\n printf(\"%s: failed to open. \\n\", filename);\n return -1;\n } else {\n printf(\"%s: opened in write mode.\\n\", filename);\n }\n /* Write content to file */\n fprintf(fp, \"%s\\n\", content);\n if( !fclose(fp) )\n printf(\"%s: closed successfully.\\n\", filename);\n return 0;\n}" }, { "code": null, "e": 1891, "s": 1824, "text": "sample.txt: opened in write mode.\nsample.txt: closed successfully." }, { "code": null, "e": 1972, "s": 1891, "text": "Se the code to get the idea how we read from a file\nMake a file (file_read.txt):" }, { "code": null, "e": 2044, "s": 1972, "text": "You have opened a file using C programming language, in read-only mode." }, { "code": null, "e": 2496, "s": 2044, "text": "#include <stdio.h>\nint main() {\n FILE *fp;\n char *filename = \"file_read.txt\";\n char ch;\n /* open for writing */\n fp = fopen(filename, \"r\");\n if (fp == NULL) {\n printf(\"%s does not exists \\n\", filename);\n return;\n } else {\n printf(\"%s: opened in read mode.\\n\\n\", filename);\n }\n while ((ch = fgetc(fp) )!= EOF) {\n printf (\"%c\", ch);\n }\n if (!fclose(fp))\n printf(\"\\n%s: closed.\\n\", filename);\n return 0;\n}" }, { "code": null, "e": 2627, "s": 2496, "text": "file_read.txt: opened in read mode.\nYou have opened a file using C programming language, in read-only mode.\nfile_read.txt: closed." }, { "code": null, "e": 2692, "s": 2627, "text": "Se the code to get the idea how we can append lines into a file." }, { "code": null, "e": 2733, "s": 2692, "text": "This text was already there in the file." }, { "code": null, "e": 3380, "s": 2733, "text": "#include <stdio.h>\nint main() {\n FILE *fp;\n char ch;\n char *filename = \"file_append.txt\";\n char *content = \"This text is appeneded later to the file, using C programming.\";\n /* open for writing */\n fp = fopen(filename, \"r\");\n printf(\"\\nContents of %s -\\n\\n\", filename);\n while ((ch = fgetc(fp) )!= EOF) {\n printf (\"%c\", ch);\n }\n fclose(fp);\n fp = fopen(filename, \"a\");\n /* Write content to file */\n fprintf(fp, \"%s\\n\", content);\n fclose(fp);\n fp = fopen(filename, \"r\");\n printf(\"\\nContents of %s -\\n\", filename);\n while ((ch = fgetc(fp) )!= EOF) {\n printf (\"%c\", ch);\n }\n fclose(fp);\n return 0;\n}" }, { "code": null, "e": 3652, "s": 3380, "text": "Contents of file_append.txt -\nThis text was already there in the file.\nAppending content to file_append.txt...\nContent of file_append.txt after 'append' operation is -\nThis text was already there in the file.\nThis text is appeneded later to the file, using C programming." } ]
Check if the given string is the same as its reflection in a mirror - GeeksforGeeks
11 Aug, 2021 Given a string S containing only uppercase English characters. The task is to find whether S is the same as its reflection in a mirror.Examples: Input: str = "AMA" Output: YES AMA is same as its reflection in the mirror. Input: str = "ZXZ" Output: NO Approach: The string obviously has to be a palindrome, but that alone is not enough. All characters in the string should be symmetric so that their reflection is also the same. The symmetric characters are AHIMOTUVWXY. Store the symmetric characters in an unordered_set. Traverse the string and check if there is any non-symmetric character present in the string. If yes then return false. Else check if the string is palindrome or not. If the string is palindrome also then return true else return false. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to check reflectionbool isReflectionEqual(string s){ // Symmetric characters unordered_set<char> symmetric = { 'A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y' }; int n = s.length(); for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.find(s[i]) == symmetric.end()) return false; string rev = s; reverse(rev.begin(), rev.end()); // Check if the string is a palindrome if (rev == s) return true; else return false;} // Driver codeint main(){ string s = "MYTYM"; if (isReflectionEqual(s)) cout << "YES"; else cout << "NO";} // Java implementation of above approachimport java.util.*; class GFG{ static String Reverse(String s) { char[] charArray = s.toCharArray(); reverse(charArray, 0, charArray.length - 1); return new String(charArray); } // Function to check reflection static boolean isReflectionEqual(String s) { HashSet<Character> symmetric = new HashSet<>(); // Symmetric characters symmetric.add('A'); symmetric.add('H'); symmetric.add('I'); symmetric.add('M'); symmetric.add('O'); symmetric.add('T'); symmetric.add('U'); symmetric.add('V'); symmetric.add('W'); symmetric.add('X'); symmetric.add('Y'); int n = s.length(); // If any non-symmetric character is for (int i = 0; i < n; i++) // present, the answer is NO { if (symmetric.contains(s.charAt(i)) == false) { return false; } } String rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev.equals(s)) { return true; } else { return false; } } // Reverse the letters of the word static void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code public static void main(String[] args) { String s = "MYTYM"; if (isReflectionEqual(s)) { System.out.println("YES"); } else { System.out.println("NO"); } }} // This code contributed by Rajput-Ji # Python3 implementation of the# above approach # Function to check reflectiondef isReflectionEqual(s): # Symmetric characters symmetric = dict() str1 = "AHIMOTUVWXY" for i in str1: symmetric[i] = 1 n = len(s) for i in range(n): # If any non-symmetric character # is present, the answer is NO if (symmetric[s[i]] == 0): return False rev = s[::-1] # Check if the is a palindrome if (rev == s): return True else: return False # Driver Codes = "MYTYM"if (isReflectionEqual(s)): print("YES")else: print("NO") # This code is contributed by Mohit Kumar // C# implementation of the above approachusing System;using System.Collections.Generic ; class GFG{ static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); } // Function to check reflection static bool isReflectionEqual(string s) { HashSet<char> symmetric = new HashSet<char>(); // Symmetric characters symmetric.Add('A'); symmetric.Add('H'); symmetric.Add('I'); symmetric.Add('M'); symmetric.Add('O'); symmetric.Add('T'); symmetric.Add('U'); symmetric.Add('V'); symmetric.Add('W'); symmetric.Add('X'); symmetric.Add('Y'); int n = s.Length; for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.Contains(s[i]) == false) return false; string rev = s; s = Reverse(s); // Check if the string is a palindrome if (rev == s) return true; else return false; } // Driver code static public void Main() { string s = "MYTYM"; if (isReflectionEqual(s)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed by Ryuga <script> // JavaScript implementation of above approach function Reverse(s) { let charArray = s.split(""); reverse(charArray, 0, charArray.length - 1); return charArray.join(""); } // Function to check reflection function isReflectionEqual(s) { let symmetric = new Set(); // Symmetric characters symmetric.add('A'); symmetric.add('H'); symmetric.add('I'); symmetric.add('M'); symmetric.add('O'); symmetric.add('T'); symmetric.add('U'); symmetric.add('V'); symmetric.add('W'); symmetric.add('X'); symmetric.add('Y'); let n = s.length; // If any non-symmetric character is for (let i = 0; i < n; i++) // present, the answer is NO { if (symmetric.has(s[i]) == false) { return false; } } let rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev==(s)) { return true; } else { return false; } } // Reverse the letters of the word function reverse(str,start,end) { // Temporary variable to store character let temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code let s = "MYTYM"; if (isReflectionEqual(s)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by unknown2108 </script> YES Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 ankthon Rajput-Ji unknown2108 pankajsharmagfg Marketing palindrome Algorithms Strings Strings palindrome Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to write a Pseudo Code? Playfair Cipher with Examples Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 24528, "s": 24500, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24675, "s": 24528, "text": "Given a string S containing only uppercase English characters. The task is to find whether S is the same as its reflection in a mirror.Examples: " }, { "code": null, "e": 24782, "s": 24675, "text": "Input: str = \"AMA\"\nOutput: YES\nAMA is same as its reflection in the mirror.\n\nInput: str = \"ZXZ\"\nOutput: NO" }, { "code": null, "e": 25002, "s": 24782, "text": "Approach: The string obviously has to be a palindrome, but that alone is not enough. All characters in the string should be symmetric so that their reflection is also the same. The symmetric characters are AHIMOTUVWXY. " }, { "code": null, "e": 25054, "s": 25002, "text": "Store the symmetric characters in an unordered_set." }, { "code": null, "e": 25173, "s": 25054, "text": "Traverse the string and check if there is any non-symmetric character present in the string. If yes then return false." }, { "code": null, "e": 25289, "s": 25173, "text": "Else check if the string is palindrome or not. If the string is palindrome also then return true else return false." }, { "code": null, "e": 25342, "s": 25289, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25346, "s": 25342, "text": "C++" }, { "code": null, "e": 25351, "s": 25346, "text": "Java" }, { "code": null, "e": 25359, "s": 25351, "text": "Python3" }, { "code": null, "e": 25362, "s": 25359, "text": "C#" }, { "code": null, "e": 25373, "s": 25362, "text": "Javascript" }, { "code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to check reflectionbool isReflectionEqual(string s){ // Symmetric characters unordered_set<char> symmetric = { 'A', 'H', 'I', 'M', 'O', 'T', 'U', 'V', 'W', 'X', 'Y' }; int n = s.length(); for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.find(s[i]) == symmetric.end()) return false; string rev = s; reverse(rev.begin(), rev.end()); // Check if the string is a palindrome if (rev == s) return true; else return false;} // Driver codeint main(){ string s = \"MYTYM\"; if (isReflectionEqual(s)) cout << \"YES\"; else cout << \"NO\";}", "e": 26182, "s": 25373, "text": null }, { "code": "// Java implementation of above approachimport java.util.*; class GFG{ static String Reverse(String s) { char[] charArray = s.toCharArray(); reverse(charArray, 0, charArray.length - 1); return new String(charArray); } // Function to check reflection static boolean isReflectionEqual(String s) { HashSet<Character> symmetric = new HashSet<>(); // Symmetric characters symmetric.add('A'); symmetric.add('H'); symmetric.add('I'); symmetric.add('M'); symmetric.add('O'); symmetric.add('T'); symmetric.add('U'); symmetric.add('V'); symmetric.add('W'); symmetric.add('X'); symmetric.add('Y'); int n = s.length(); // If any non-symmetric character is for (int i = 0; i < n; i++) // present, the answer is NO { if (symmetric.contains(s.charAt(i)) == false) { return false; } } String rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev.equals(s)) { return true; } else { return false; } } // Reverse the letters of the word static void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code public static void main(String[] args) { String s = \"MYTYM\"; if (isReflectionEqual(s)) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } }} // This code contributed by Rajput-Ji", "e": 28093, "s": 26182, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to check reflectiondef isReflectionEqual(s): # Symmetric characters symmetric = dict() str1 = \"AHIMOTUVWXY\" for i in str1: symmetric[i] = 1 n = len(s) for i in range(n): # If any non-symmetric character # is present, the answer is NO if (symmetric[s[i]] == 0): return False rev = s[::-1] # Check if the is a palindrome if (rev == s): return True else: return False # Driver Codes = \"MYTYM\"if (isReflectionEqual(s)): print(\"YES\")else: print(\"NO\") # This code is contributed by Mohit Kumar", "e": 28745, "s": 28093, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic ; class GFG{ static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); } // Function to check reflection static bool isReflectionEqual(string s) { HashSet<char> symmetric = new HashSet<char>(); // Symmetric characters symmetric.Add('A'); symmetric.Add('H'); symmetric.Add('I'); symmetric.Add('M'); symmetric.Add('O'); symmetric.Add('T'); symmetric.Add('U'); symmetric.Add('V'); symmetric.Add('W'); symmetric.Add('X'); symmetric.Add('Y'); int n = s.Length; for (int i = 0; i < n; i++) // If any non-symmetric character is // present, the answer is NO if (symmetric.Contains(s[i]) == false) return false; string rev = s; s = Reverse(s); // Check if the string is a palindrome if (rev == s) return true; else return false; } // Driver code static public void Main() { string s = \"MYTYM\"; if (isReflectionEqual(s)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by Ryuga", "e": 30166, "s": 28745, "text": null }, { "code": "<script> // JavaScript implementation of above approach function Reverse(s) { let charArray = s.split(\"\"); reverse(charArray, 0, charArray.length - 1); return charArray.join(\"\"); } // Function to check reflection function isReflectionEqual(s) { let symmetric = new Set(); // Symmetric characters symmetric.add('A'); symmetric.add('H'); symmetric.add('I'); symmetric.add('M'); symmetric.add('O'); symmetric.add('T'); symmetric.add('U'); symmetric.add('V'); symmetric.add('W'); symmetric.add('X'); symmetric.add('Y'); let n = s.length; // If any non-symmetric character is for (let i = 0; i < n; i++) // present, the answer is NO { if (symmetric.has(s[i]) == false) { return false; } } let rev = s; s = Reverse(s); // Check if the String is a palindrome if (rev==(s)) { return true; } else { return false; } } // Reverse the letters of the word function reverse(str,start,end) { // Temporary variable to store character let temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // Driver code let s = \"MYTYM\"; if (isReflectionEqual(s)) { document.write(\"YES\"); } else { document.write(\"NO\"); } // This code is contributed by unknown2108 </script>", "e": 31934, "s": 30166, "text": null }, { "code": null, "e": 31938, "s": 31934, "text": "YES" }, { "code": null, "e": 31983, "s": 31940, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31998, "s": 31983, "text": "mohit kumar 29" }, { "code": null, "e": 32006, "s": 31998, "text": "ankthon" }, { "code": null, "e": 32016, "s": 32006, "text": "Rajput-Ji" }, { "code": null, "e": 32028, "s": 32016, "text": "unknown2108" }, { "code": null, "e": 32044, "s": 32028, "text": "pankajsharmagfg" }, { "code": null, "e": 32054, "s": 32044, "text": "Marketing" }, { "code": null, "e": 32065, "s": 32054, "text": "palindrome" }, { "code": null, "e": 32076, "s": 32065, "text": "Algorithms" }, { "code": null, "e": 32084, "s": 32076, "text": "Strings" }, { "code": null, "e": 32092, "s": 32084, "text": "Strings" }, { "code": null, "e": 32103, "s": 32092, "text": "palindrome" }, { "code": null, "e": 32114, "s": 32103, "text": "Algorithms" }, { "code": null, "e": 32212, "s": 32114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32221, "s": 32212, "text": "Comments" }, { "code": null, "e": 32234, "s": 32221, "text": "Old Comments" }, { "code": null, "e": 32283, "s": 32234, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32308, "s": 32283, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32335, "s": 32308, "text": "Introduction to Algorithms" }, { "code": null, "e": 32363, "s": 32335, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32393, "s": 32363, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 32418, "s": 32393, "text": "Reverse a string in Java" }, { "code": null, "e": 32464, "s": 32418, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32498, "s": 32464, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32513, "s": 32498, "text": "C++ Data Types" } ]
Check if a point having maximum X and Y coordinates exists or not - GeeksforGeeks
29 Nov, 2021 Given a 2D array arr[] consisting of N coordinates of the form (X, Y), the task is to find a coordinate from the given array such that the X-coordinate of this point is greater than all other X-coordinates and the Y-coordinate of this point is greater than all other Y-coordinates. If no such point exists, print -1. Examples: Input: arr[][] = {(1, 2), (2, 1), (3, 4), (4, 3), (5, 5)}Output: (5, 5)Explanation:The maximum X-coordinate is 5 and the maximum Y-coordinate is 5.Since the point (5, 5) is present in the array, print (5, 5) as the required answer. Input: arr[] = {(5, 3), (3, 5)}Output: -1Explanation:The maximum X-coordinate is 5 and maximum Y-coordinate is 5. Since+ (5, 5) is not present. Therefore, print -1. Naive Approach: The simplest approach is to traverse the array and for each point, check if it is the maximum X and Y-coordinates or not. If no such point exists, print -1. Otherwise, print the point as the required answer. 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; // Initialize INF as infinityint INF = INT_MAX; // Function to return the point having// maximum X and Y coordinatesint* findMaxPoint(int arr[][2], int i, int n){ // Base Case if (i == n) { arr[0][0] = INF; arr[0][1] = INF; return arr[0]; } // Stores if valid point exists bool flag = true; // If point arr[i] is valid for(int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointvoid findMaxPoints(int arr[][2], int n){ // Stores the point with maximum // X and Y-coordinates int ans[2]; memcpy(ans, findMaxPoint(arr, 0, n), 2 * sizeof(int)); // If no required point exists if (ans[0] == INF) { cout << -1; } else { cout << "(" << ans[0] << " " << ans[1] << ")"; }} // Driver Codeint main(){ // Given array of points int arr[][2] = { { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findMaxPoints(arr, N); return 0;} // This code is contributed by subhammahato348 // Java program for the above approach import java.io.*; class GFG { // Initialize INF as infinity static int INF = Integer.MAX_VALUE; // Function to return the point having // maximum X and Y coordinates static int[] findMaxPoint( int arr[][], int i, int n) { // Base Case if (i == n) return new int[] { INF, INF }; // Stores if valid point exists boolean flag = true; // If point arr[i] is valid for (int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n); } // Function to find the required point static void findMaxPoints(int arr[][], int n) { // Stores the point with maximum // X and Y-coordinates int ans[] = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { System.out.println(-1); } else { System.out.println( "(" + ans[0] + " " + ans[1] + ")"); } } // Driver Code public static void main(String[] args) { // Given array of points int arr[][] = new int[][] {{ 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 }}; int N = arr.length; // Function Call findMaxPoints(arr, N); }} # Python3 program for the above approachimport sys # Initialize INF as infinityINF = sys.maxsize; # Function to return the pohaving# maximum X and Y coordinatesdef findMaxPoint(arr, i, n): # Base Case if (i == n): return [INF, INF] # Stores if valid poexists flag = True; # If poarr[i] is valid for j in range(n): # Check for the same point if (j == i): continue; # Check for a valid point if (arr[j][0] >= arr[i][0] or arr[j][1] >= arr[i][1]): flag = False; break; # If current pois the # required point if (flag): return arr[i]; # Otherwise return findMaxPoint(arr, i + 1, n); # Function to find the required pointdef findMaxPoints(arr, n): # Stores the powith maximum # X and Y-coordinates ans = findMaxPoint(arr, 0, n); # If no required poexists if (ans[0] == INF): print(-1); else: print("(" , ans[0] , " " , ans[1] , ")"); # Driver Codeif __name__ == '__main__': # Given array of points arr = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]; N = len(arr); # Function Call findMaxPoints(arr, N); # This code is contributed by shikhasingrajput // C# program for the above approachusing System; class GFG{ // Initialize INF as infinitystatic int INF = int.MaxValue; // Function to return the point having// maximum X and Y coordinatesstatic int[] findMaxPoint(int [,]arr, int i, int n){ // Base Case if (i == n) return new int[]{INF, INF}; // Stores if valid point exists bool flag = true; // If point arr[i] is valid for(int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j, 0] >= arr[i, 0] || arr[j, 1] >= arr[i, 1]) { flag = false; break; } } // If current point is the // required point int []ans = new int[arr.GetLength(1)]; if (flag) { for(int k = 0; k < ans.GetLength(0); k++) ans[k] = arr[i, k]; return ans; } // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointstatic void findMaxPoints(int [,]arr, int n){ // Stores the point with maximum // X and Y-coordinates int []ans = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { Console.WriteLine(-1); } else { Console.WriteLine("(" + ans[0] + " " + ans[1] + ")"); }} // Driver Codepublic static void Main(String[] args){ // Given array of points int [,]arr = new int[,]{ { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; int N = arr.GetLength(0); // Function Call findMaxPoints(arr, N);}} // This code is contributed by Princi Singh <script> // Javascript program for the above approach // Initialize INF as infinitylet INF = Number.MAX_VALUE; // Function to return the point having// maximum X and Y coordinatesfunction findMaxPoint(arr, i, n){ // Base Case if (i == n) return [INF, INF]; // Stores if valid point exists let flag = true; // If point arr[i] is valid for(let j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointfunction findMaxPoints(arr, n){ // Stores the point with maximum // X and Y-coordinates let ans = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { document.write(-1); } else { document.write("(" + ans[0] + " " + ans[1] + ")"); }} // Driver code // Given array of pointslet arr = [ [ 1, 2 ], [ 2, 1 ], [ 3, 4 ], [ 4, 3 ], [ 5, 5 ] ]; let N = arr.length; // Function CallfindMaxPoints(arr, N); // This code is contributed by splevel62 </script> (5 5) Time Complexity: O(N2) where N is the length of the given array.Auxiliary Space: O(N) Efficient Approach: The idea is to find the maximum X and Y coordinates. Let them be maxX and maxY. Again traverse the given array checking if the point (maxX, maxY) is present. Follow the below steps to solve the problem: Traverse the given array arr[] and find the maximum X and Y coordinates. Let them be maxX and maxY.Again traverse the array arr[] from i = 0 to N-1 checking if (arr[i].X, arr[i].Y) is equals to (maxX, maxY).If the (maxX, maxY) is present in the array arr[], print (maxX, maxY) else print -1. Traverse the given array arr[] and find the maximum X and Y coordinates. Let them be maxX and maxY. Again traverse the array arr[] from i = 0 to N-1 checking if (arr[i].X, arr[i].Y) is equals to (maxX, maxY). If the (maxX, maxY) is present in the array arr[], print (maxX, maxY) else print -1. Below is the implementation of the above approach: C++ Java Python3 C# // C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define N 5#define P 2 // Function to find the point having// max X and Y coordinatesvoid findMaxPoint(int arr[N][P]){ // Initialize maxX and maxY int maxX = INT_MIN; int maxY = INT_MIN; // Length of the given array int n = N; // Get maximum X & Y coordinates for(int i = 0; i < n; i++) { maxX = max(maxX, arr[i][0]); maxY = max(maxY, arr[i][1]); } // Check if the required point // i.e., (maxX, maxY) is present for(int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i][0] && maxY == arr[i][1]) { cout << "(" << maxX << ", " << maxY << ")"; return; } } // If no such point exists cout << (-1);} // Driver Codeint main(){ // Given array of points int arr[N][P] = { { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; // Print answer findMaxPoint(arr);} // This code is contributed by 29AjayKumar // Java program for the above approach import java.io.*; class GFG { // Function to find the point having // max X and Y coordinates static void findMaxPoint(int arr[][]) { // Initialize maxX and maxY int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; // Length of the given array int n = arr.length; // Get maximum X & Y coordinates for (int i = 0; i < n; i++) { maxX = Math.max(maxX, arr[i][0]); maxY = Math.max(maxY, arr[i][1]); } // Check if the required point // i.e., (maxX, maxY) is present for (int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i][0] && maxY == arr[i][1]) { System.out.println( "(" + maxX + ", " + maxY + ")"); return; } } // If no such point exists System.out.println(-1); } // Driver Code public static void main(String[] args) { // Given array of points int arr[][] = new int[][] {{ 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 }}; // Print answer findMaxPoint(arr); }} # Python3 program for the above approachimport sys; # Function to find the pohaving# max X and Y coordinatesdef findMaxPoint(arr): # Initialize maxX and maxY maxX = -sys.maxsize; maxY = -sys.maxsize; # Length of the given array n = len(arr); # Get maximum X & Y coordinates for i in range(n): maxX = max(maxX, arr[i][0]); maxY = max(maxY, arr[i][1]); # Check if the required point # i.e., (maxX, maxY) is present for i in range(n): # If powith maximum X and # Y coordinates is present if (maxX == arr[i][0] and maxY == arr[i][1]): print("(" , maxX , ", " , maxY , ")"); return; # If no such poexists print(-1); # Driver Codeif __name__ == '__main__': # Given array of points arr = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]; # Pranswer findMaxPoint(arr); # This code is contributed by gauravrajput1 // C# program for the above approachusing System; class GFG{ // Function to find the point having// max X and Y coordinatesstatic void findMaxPoint(int [,]arr){ // Initialize maxX and maxY int maxX = int.MinValue; int maxY = int.MinValue; // Length of the given array int n = arr.GetLength(0); // Get maximum X & Y coordinates for(int i = 0; i < n; i++) { maxX = Math.Max(maxX, arr[i, 0]); maxY = Math.Max(maxY, arr[i, 1]); } // Check if the required point // i.e., (maxX, maxY) is present for(int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i, 0] && maxY == arr[i, 1]) { Console.WriteLine("(" + maxX + ", " + maxY + ")"); return; } } // If no such point exists Console.WriteLine(-1);} // Driver Codepublic static void Main(String[] args){ // Given array of points int [,]arr = new int[,]{ { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; // Print answer findMaxPoint(arr);}} // This code is contributed by Amit Katiyar (5, 5) Time Complexity: O(N)Auxiliary Space: O(N) princi singh amit143katiyar 29AjayKumar GauravRajput1 shikhasingrajput subhammahato348 splevel62 Kirti_Mangal abhishek0719kadiyan array-traversal-question Arrays Mathematical School Programming Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25306, "s": 25278, "text": "\n29 Nov, 2021" }, { "code": null, "e": 25623, "s": 25306, "text": "Given a 2D array arr[] consisting of N coordinates of the form (X, Y), the task is to find a coordinate from the given array such that the X-coordinate of this point is greater than all other X-coordinates and the Y-coordinate of this point is greater than all other Y-coordinates. If no such point exists, print -1." }, { "code": null, "e": 25633, "s": 25623, "text": "Examples:" }, { "code": null, "e": 25865, "s": 25633, "text": "Input: arr[][] = {(1, 2), (2, 1), (3, 4), (4, 3), (5, 5)}Output: (5, 5)Explanation:The maximum X-coordinate is 5 and the maximum Y-coordinate is 5.Since the point (5, 5) is present in the array, print (5, 5) as the required answer." }, { "code": null, "e": 26031, "s": 25865, "text": "Input: arr[] = {(5, 3), (3, 5)}Output: -1Explanation:The maximum X-coordinate is 5 and maximum Y-coordinate is 5. Since+ (5, 5) is not present. Therefore, print -1. " }, { "code": null, "e": 26255, "s": 26031, "text": "Naive Approach: The simplest approach is to traverse the array and for each point, check if it is the maximum X and Y-coordinates or not. If no such point exists, print -1. Otherwise, print the point as the required answer." }, { "code": null, "e": 26306, "s": 26255, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26310, "s": 26306, "text": "C++" }, { "code": null, "e": 26315, "s": 26310, "text": "Java" }, { "code": null, "e": 26323, "s": 26315, "text": "Python3" }, { "code": null, "e": 26326, "s": 26323, "text": "C#" }, { "code": null, "e": 26337, "s": 26326, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Initialize INF as infinityint INF = INT_MAX; // Function to return the point having// maximum X and Y coordinatesint* findMaxPoint(int arr[][2], int i, int n){ // Base Case if (i == n) { arr[0][0] = INF; arr[0][1] = INF; return arr[0]; } // Stores if valid point exists bool flag = true; // If point arr[i] is valid for(int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointvoid findMaxPoints(int arr[][2], int n){ // Stores the point with maximum // X and Y-coordinates int ans[2]; memcpy(ans, findMaxPoint(arr, 0, n), 2 * sizeof(int)); // If no required point exists if (ans[0] == INF) { cout << -1; } else { cout << \"(\" << ans[0] << \" \" << ans[1] << \")\"; }} // Driver Codeint main(){ // Given array of points int arr[][2] = { { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findMaxPoints(arr, N); return 0;} // This code is contributed by subhammahato348", "e": 27949, "s": 26337, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { // Initialize INF as infinity static int INF = Integer.MAX_VALUE; // Function to return the point having // maximum X and Y coordinates static int[] findMaxPoint( int arr[][], int i, int n) { // Base Case if (i == n) return new int[] { INF, INF }; // Stores if valid point exists boolean flag = true; // If point arr[i] is valid for (int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n); } // Function to find the required point static void findMaxPoints(int arr[][], int n) { // Stores the point with maximum // X and Y-coordinates int ans[] = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { System.out.println(-1); } else { System.out.println( \"(\" + ans[0] + \" \" + ans[1] + \")\"); } } // Driver Code public static void main(String[] args) { // Given array of points int arr[][] = new int[][] {{ 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 }}; int N = arr.length; // Function Call findMaxPoints(arr, N); }}", "e": 29729, "s": 27949, "text": null }, { "code": "# Python3 program for the above approachimport sys # Initialize INF as infinityINF = sys.maxsize; # Function to return the pohaving# maximum X and Y coordinatesdef findMaxPoint(arr, i, n): # Base Case if (i == n): return [INF, INF] # Stores if valid poexists flag = True; # If poarr[i] is valid for j in range(n): # Check for the same point if (j == i): continue; # Check for a valid point if (arr[j][0] >= arr[i][0] or arr[j][1] >= arr[i][1]): flag = False; break; # If current pois the # required point if (flag): return arr[i]; # Otherwise return findMaxPoint(arr, i + 1, n); # Function to find the required pointdef findMaxPoints(arr, n): # Stores the powith maximum # X and Y-coordinates ans = findMaxPoint(arr, 0, n); # If no required poexists if (ans[0] == INF): print(-1); else: print(\"(\" , ans[0] , \" \" , ans[1] , \")\"); # Driver Codeif __name__ == '__main__': # Given array of points arr = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]; N = len(arr); # Function Call findMaxPoints(arr, N); # This code is contributed by shikhasingrajput", "e": 30984, "s": 29729, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Initialize INF as infinitystatic int INF = int.MaxValue; // Function to return the point having// maximum X and Y coordinatesstatic int[] findMaxPoint(int [,]arr, int i, int n){ // Base Case if (i == n) return new int[]{INF, INF}; // Stores if valid point exists bool flag = true; // If point arr[i] is valid for(int j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j, 0] >= arr[i, 0] || arr[j, 1] >= arr[i, 1]) { flag = false; break; } } // If current point is the // required point int []ans = new int[arr.GetLength(1)]; if (flag) { for(int k = 0; k < ans.GetLength(0); k++) ans[k] = arr[i, k]; return ans; } // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointstatic void findMaxPoints(int [,]arr, int n){ // Stores the point with maximum // X and Y-coordinates int []ans = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { Console.WriteLine(-1); } else { Console.WriteLine(\"(\" + ans[0] + \" \" + ans[1] + \")\"); }} // Driver Codepublic static void Main(String[] args){ // Given array of points int [,]arr = new int[,]{ { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; int N = arr.GetLength(0); // Function Call findMaxPoints(arr, N);}} // This code is contributed by Princi Singh", "e": 32760, "s": 30984, "text": null }, { "code": "<script> // Javascript program for the above approach // Initialize INF as infinitylet INF = Number.MAX_VALUE; // Function to return the point having// maximum X and Y coordinatesfunction findMaxPoint(arr, i, n){ // Base Case if (i == n) return [INF, INF]; // Stores if valid point exists let flag = true; // If point arr[i] is valid for(let j = 0; j < n; j++) { // Check for the same point if (j == i) continue; // Check for a valid point if (arr[j][0] >= arr[i][0] || arr[j][1] >= arr[i][1]) { flag = false; break; } } // If current point is the // required point if (flag) return arr[i]; // Otherwise return findMaxPoint(arr, i + 1, n);} // Function to find the required pointfunction findMaxPoints(arr, n){ // Stores the point with maximum // X and Y-coordinates let ans = findMaxPoint(arr, 0, n); // If no required point exists if (ans[0] == INF) { document.write(-1); } else { document.write(\"(\" + ans[0] + \" \" + ans[1] + \")\"); }} // Driver code // Given array of pointslet arr = [ [ 1, 2 ], [ 2, 1 ], [ 3, 4 ], [ 4, 3 ], [ 5, 5 ] ]; let N = arr.length; // Function CallfindMaxPoints(arr, N); // This code is contributed by splevel62 </script>", "e": 34168, "s": 32760, "text": null }, { "code": null, "e": 34174, "s": 34168, "text": "(5 5)" }, { "code": null, "e": 34262, "s": 34176, "text": "Time Complexity: O(N2) where N is the length of the given array.Auxiliary Space: O(N)" }, { "code": null, "e": 34485, "s": 34262, "text": "Efficient Approach: The idea is to find the maximum X and Y coordinates. Let them be maxX and maxY. Again traverse the given array checking if the point (maxX, maxY) is present. Follow the below steps to solve the problem:" }, { "code": null, "e": 34777, "s": 34485, "text": "Traverse the given array arr[] and find the maximum X and Y coordinates. Let them be maxX and maxY.Again traverse the array arr[] from i = 0 to N-1 checking if (arr[i].X, arr[i].Y) is equals to (maxX, maxY).If the (maxX, maxY) is present in the array arr[], print (maxX, maxY) else print -1." }, { "code": null, "e": 34877, "s": 34777, "text": "Traverse the given array arr[] and find the maximum X and Y coordinates. Let them be maxX and maxY." }, { "code": null, "e": 34986, "s": 34877, "text": "Again traverse the array arr[] from i = 0 to N-1 checking if (arr[i].X, arr[i].Y) is equals to (maxX, maxY)." }, { "code": null, "e": 35071, "s": 34986, "text": "If the (maxX, maxY) is present in the array arr[], print (maxX, maxY) else print -1." }, { "code": null, "e": 35122, "s": 35071, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35126, "s": 35122, "text": "C++" }, { "code": null, "e": 35131, "s": 35126, "text": "Java" }, { "code": null, "e": 35139, "s": 35131, "text": "Python3" }, { "code": null, "e": 35142, "s": 35139, "text": "C#" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define N 5#define P 2 // Function to find the point having// max X and Y coordinatesvoid findMaxPoint(int arr[N][P]){ // Initialize maxX and maxY int maxX = INT_MIN; int maxY = INT_MIN; // Length of the given array int n = N; // Get maximum X & Y coordinates for(int i = 0; i < n; i++) { maxX = max(maxX, arr[i][0]); maxY = max(maxY, arr[i][1]); } // Check if the required point // i.e., (maxX, maxY) is present for(int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i][0] && maxY == arr[i][1]) { cout << \"(\" << maxX << \", \" << maxY << \")\"; return; } } // If no such point exists cout << (-1);} // Driver Codeint main(){ // Given array of points int arr[N][P] = { { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; // Print answer findMaxPoint(arr);} // This code is contributed by 29AjayKumar", "e": 36317, "s": 35142, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { // Function to find the point having // max X and Y coordinates static void findMaxPoint(int arr[][]) { // Initialize maxX and maxY int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; // Length of the given array int n = arr.length; // Get maximum X & Y coordinates for (int i = 0; i < n; i++) { maxX = Math.max(maxX, arr[i][0]); maxY = Math.max(maxY, arr[i][1]); } // Check if the required point // i.e., (maxX, maxY) is present for (int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i][0] && maxY == arr[i][1]) { System.out.println( \"(\" + maxX + \", \" + maxY + \")\"); return; } } // If no such point exists System.out.println(-1); } // Driver Code public static void main(String[] args) { // Given array of points int arr[][] = new int[][] {{ 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 }}; // Print answer findMaxPoint(arr); }}", "e": 37653, "s": 36317, "text": null }, { "code": "# Python3 program for the above approachimport sys; # Function to find the pohaving# max X and Y coordinatesdef findMaxPoint(arr): # Initialize maxX and maxY maxX = -sys.maxsize; maxY = -sys.maxsize; # Length of the given array n = len(arr); # Get maximum X & Y coordinates for i in range(n): maxX = max(maxX, arr[i][0]); maxY = max(maxY, arr[i][1]); # Check if the required point # i.e., (maxX, maxY) is present for i in range(n): # If powith maximum X and # Y coordinates is present if (maxX == arr[i][0] and maxY == arr[i][1]): print(\"(\" , maxX , \", \" , maxY , \")\"); return; # If no such poexists print(-1); # Driver Codeif __name__ == '__main__': # Given array of points arr = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]; # Pranswer findMaxPoint(arr); # This code is contributed by gauravrajput1", "e": 38569, "s": 37653, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the point having// max X and Y coordinatesstatic void findMaxPoint(int [,]arr){ // Initialize maxX and maxY int maxX = int.MinValue; int maxY = int.MinValue; // Length of the given array int n = arr.GetLength(0); // Get maximum X & Y coordinates for(int i = 0; i < n; i++) { maxX = Math.Max(maxX, arr[i, 0]); maxY = Math.Max(maxY, arr[i, 1]); } // Check if the required point // i.e., (maxX, maxY) is present for(int i = 0; i < n; i++) { // If point with maximum X and // Y coordinates is present if (maxX == arr[i, 0] && maxY == arr[i, 1]) { Console.WriteLine(\"(\" + maxX + \", \" + maxY + \")\"); return; } } // If no such point exists Console.WriteLine(-1);} // Driver Codepublic static void Main(String[] args){ // Given array of points int [,]arr = new int[,]{ { 1, 2 }, { 2, 1 }, { 3, 4 }, { 4, 3 }, { 5, 5 } }; // Print answer findMaxPoint(arr);}} // This code is contributed by Amit Katiyar", "e": 39801, "s": 38569, "text": null }, { "code": null, "e": 39808, "s": 39801, "text": "(5, 5)" }, { "code": null, "e": 39853, "s": 39810, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 39866, "s": 39853, "text": "princi singh" }, { "code": null, "e": 39881, "s": 39866, "text": "amit143katiyar" }, { "code": null, "e": 39893, "s": 39881, "text": "29AjayKumar" }, { "code": null, "e": 39907, "s": 39893, "text": "GauravRajput1" }, { "code": null, "e": 39924, "s": 39907, "text": "shikhasingrajput" }, { "code": null, "e": 39940, "s": 39924, "text": "subhammahato348" }, { "code": null, "e": 39950, "s": 39940, "text": "splevel62" }, { "code": null, "e": 39963, "s": 39950, "text": "Kirti_Mangal" }, { "code": null, "e": 39983, "s": 39963, "text": "abhishek0719kadiyan" }, { "code": null, "e": 40008, "s": 39983, "text": "array-traversal-question" }, { "code": null, "e": 40015, "s": 40008, "text": "Arrays" }, { "code": null, "e": 40028, "s": 40015, "text": "Mathematical" }, { "code": null, "e": 40047, "s": 40028, "text": "School Programming" }, { "code": null, "e": 40057, "s": 40047, "text": "Searching" }, { "code": null, "e": 40064, "s": 40057, "text": "Arrays" }, { "code": null, "e": 40074, "s": 40064, "text": "Searching" }, { "code": null, "e": 40087, "s": 40074, "text": "Mathematical" }, { "code": null, "e": 40185, "s": 40087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40194, "s": 40185, "text": "Comments" }, { "code": null, "e": 40207, "s": 40194, "text": "Old Comments" }, { "code": null, "e": 40255, "s": 40207, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 40299, "s": 40255, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40331, "s": 40299, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40354, "s": 40331, "text": "Introduction to Arrays" }, { "code": null, "e": 40368, "s": 40354, "text": "Linear Search" }, { "code": null, "e": 40398, "s": 40368, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 40458, "s": 40398, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40473, "s": 40458, "text": "C++ Data Types" }, { "code": null, "e": 40516, "s": 40473, "text": "Set in C++ Standard Template Library (STL)" } ]
How to clear cache memory using JavaScript? - GeeksforGeeks
27 Mar, 2020 Unlike mobile applications, a web browser doesn’t allow to clear its cache memory. Though we cannot clear all cache of the client browser it is still possible to load the webpage without caching by using meta tags in the HTML code. The only way to do this is by making few changes in the code which says the browser not remember the recently loaded memory which is nothing but the chache memory. The following are two examples that explainNOTE: The following codes cannot be run as it is and does not have an output. It has to added to an already existing code to see the Outputs. Method 1: <meta http-equiv='cache-control' content='no-cache'><meta http-equiv='expires' content='0'><meta http-equiv='pragma' content='no-cache'> Add this part of HTML code which makes the browser to not record the cache memory. Method 2:Appending a parameter to the filename in the script tag. Change it when the file changes. Example:Let this be the name of the file. Every time you load this page just change the version of the script. <script src = "filename.js?version = 1.0"></script> The next time you load this page it should be something like this. <script src = "newfile.js?version = 1.1"></script> NOTE: A browser is designed in such a way that it saves all the temporary cache. It is so because cache memory is the main reason for the website to load faster. Hence there is no direct way to permanently delete it’s cache memory unless certain codings are changed in your HTML code. There may be few other ways to achieve this, but these two are the easiest and most effective one. JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24460, "s": 24432, "text": "\n27 Mar, 2020" }, { "code": null, "e": 24692, "s": 24460, "text": "Unlike mobile applications, a web browser doesn’t allow to clear its cache memory. Though we cannot clear all cache of the client browser it is still possible to load the webpage without caching by using meta tags in the HTML code." }, { "code": null, "e": 24856, "s": 24692, "text": "The only way to do this is by making few changes in the code which says the browser not remember the recently loaded memory which is nothing but the chache memory." }, { "code": null, "e": 25041, "s": 24856, "text": "The following are two examples that explainNOTE: The following codes cannot be run as it is and does not have an output. It has to added to an already existing code to see the Outputs." }, { "code": null, "e": 25051, "s": 25041, "text": "Method 1:" }, { "code": "<meta http-equiv='cache-control' content='no-cache'><meta http-equiv='expires' content='0'><meta http-equiv='pragma' content='no-cache'>", "e": 25188, "s": 25051, "text": null }, { "code": null, "e": 25271, "s": 25188, "text": "Add this part of HTML code which makes the browser to not record the cache memory." }, { "code": null, "e": 25370, "s": 25271, "text": "Method 2:Appending a parameter to the filename in the script tag. Change it when the file changes." }, { "code": null, "e": 25481, "s": 25370, "text": "Example:Let this be the name of the file. Every time you load this page just change the version of the script." }, { "code": "<script src = \"filename.js?version = 1.0\"></script>", "e": 25533, "s": 25481, "text": null }, { "code": null, "e": 25600, "s": 25533, "text": "The next time you load this page it should be something like this." }, { "code": "<script src = \"newfile.js?version = 1.1\"></script>", "e": 25651, "s": 25600, "text": null }, { "code": null, "e": 25657, "s": 25651, "text": "NOTE:" }, { "code": null, "e": 25732, "s": 25657, "text": "A browser is designed in such a way that it saves all the temporary cache." }, { "code": null, "e": 25813, "s": 25732, "text": "It is so because cache memory is the main reason for the website to load faster." }, { "code": null, "e": 25936, "s": 25813, "text": "Hence there is no direct way to permanently delete it’s cache memory unless certain codings are changed in your HTML code." }, { "code": null, "e": 26035, "s": 25936, "text": "There may be few other ways to achieve this, but these two are the easiest and most effective one." }, { "code": null, "e": 26051, "s": 26035, "text": "JavaScript-Misc" }, { "code": null, "e": 26058, "s": 26051, "text": "Picked" }, { "code": null, "e": 26069, "s": 26058, "text": "JavaScript" }, { "code": null, "e": 26086, "s": 26069, "text": "Web Technologies" }, { "code": null, "e": 26184, "s": 26086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26224, "s": 26184, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26269, "s": 26224, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26330, "s": 26269, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26402, "s": 26330, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26454, "s": 26402, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26494, "s": 26454, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26527, "s": 26494, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26572, "s": 26527, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26615, "s": 26572, "text": "How to fetch data from an API in ReactJS ?" } ]
SELECT Statement and its Clauses in DBMS
The select statement is used to get the required data from the database according to the conditions, if any. This data is returned in the form of a table. The basic syntax of the select statement is − Select column 1, column 2 ... column N From table_name An example of the select statement is − <Student> Query − Select Student_Name From Student This query yields the following result − The example of select statement given above is quite simple and not that useful in practice. So, there are many other clauses associated with select statement that make it more meaningful. Some of these are − The where clause is used to filter out data i.e it returns information that satisfies a certain condition. For example − Select Student_Name From Student Where Student_Marks >50 This query will return the following result: This is mostly used with aggregate functions to group the result set according to the value of a column. For example − Select Count (Student_Number), Student_MajorSubject From Student Group by Student_MajorSubject This query will return the following result − This is used along with Group By clause because Where clause could not be used by aggregate functions. For Example − Select Count(Student_number), Student_MajorSubject From Student Group by Student_MajorSubject Having Count(Student_Number) > 2 This query will return the following result − The order by keyword is used to sort the results in ascending or descending order. By default, the order is assumed to be ascending. For Example − Select Student_Name From Student Where Student_Marks>50 Order by Student_Marks This query will return the following result −
[ { "code": null, "e": 1217, "s": 1062, "text": "The select statement is used to get the required data from the database according to the conditions, if any. This data is returned in the form of a table." }, { "code": null, "e": 1263, "s": 1217, "text": "The basic syntax of the select statement is −" }, { "code": null, "e": 1318, "s": 1263, "text": "Select column 1, column 2 ... column N\nFrom table_name" }, { "code": null, "e": 1358, "s": 1318, "text": "An example of the select statement is −" }, { "code": null, "e": 1368, "s": 1358, "text": "<Student>" }, { "code": null, "e": 1376, "s": 1368, "text": "Query −" }, { "code": null, "e": 1409, "s": 1376, "text": "Select Student_Name\nFrom Student" }, { "code": null, "e": 1450, "s": 1409, "text": "This query yields the following result −" }, { "code": null, "e": 1659, "s": 1450, "text": "The example of select statement given above is quite simple and not that useful in practice. So, there are many other clauses associated with select statement that make it more meaningful. Some of these are −" }, { "code": null, "e": 1780, "s": 1659, "text": "The where clause is used to filter out data i.e it returns information that satisfies a certain condition. For example −" }, { "code": null, "e": 1837, "s": 1780, "text": "Select Student_Name\nFrom Student\nWhere Student_Marks >50" }, { "code": null, "e": 1882, "s": 1837, "text": "This query will return the following result:" }, { "code": null, "e": 2001, "s": 1882, "text": "This is mostly used with aggregate functions to group the result set according to the value of a column. For example −" }, { "code": null, "e": 2096, "s": 2001, "text": "Select Count (Student_Number), Student_MajorSubject\nFrom Student\nGroup by Student_MajorSubject" }, { "code": null, "e": 2142, "s": 2096, "text": "This query will return the following result −" }, { "code": null, "e": 2260, "s": 2142, "text": "This is used along with Group By clause because Where clause could not be used by aggregate functions. For Example − " }, { "code": null, "e": 2387, "s": 2260, "text": "Select Count(Student_number), Student_MajorSubject\nFrom Student\nGroup by Student_MajorSubject\nHaving Count(Student_Number) > 2" }, { "code": null, "e": 2433, "s": 2387, "text": "This query will return the following result −" }, { "code": null, "e": 2580, "s": 2433, "text": "The order by keyword is used to sort the results in ascending or descending order. By default, the order is assumed to be ascending. For Example −" }, { "code": null, "e": 2659, "s": 2580, "text": "Select Student_Name\nFrom Student\nWhere Student_Marks>50\nOrder by Student_Marks" }, { "code": null, "e": 2705, "s": 2659, "text": "This query will return the following result −" } ]
Remove three consecutive duplicates from string - GeeksforGeeks
06 Jul, 2021 Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is.Examples: Input : aabbbaccddddc Output :ccdc Input :aabbaccddc Output :aabbaccddc Explanation : We insert the characters of string one by one to vector and keep on checking the size of vector. If the size of vector is greater than 2, then we will check whether the last 3 characters of the string are same or not. If the characters are same then we will move three steps backwards in array using resize() else not. C++ Java Python3 C# PHP Javascript // C++ program to remove three consecutive// duplicates#include <bits/stdc++.h>using namespace std; // function to remove three consecutive// duplicatesvoid remove3ConsecutiveDuplicates(string str){ vector<char> v; for (int i = 0; i < str.size(); ++i) { v.push_back(str[i]); if (v.size() > 2) { int sz = v.size(); // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.resize(sz - 3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.size(); ++i) cout << v[i];} // driver codeint main(){ string str = "aabbbaccddddc"; remove3ConsecutiveDuplicates(str); return 0;} // Java program to remove three consecutive// duplicatesimport java.util.*; class GFG{ // function to remove three consecutive// duplicatesstatic void remove3ConsecutiveDuplicates(String str){ Vector<Character> v = new Vector<>(); for (int i = 0; i < str.length(); ++i) { v.add(str.charAt(i)); if (v.size() > 2) { int sz = v.size(); // removing three consecutive duplicates if (v.get(sz - 1) == v.get(sz - 2) && v.get(sz - 2) == v.get(sz - 3)) { v.setSize(sz - 3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.size(); ++i) System.out.print(v.get(i));} // Driver codepublic static void main(String[] args){ String str = "aabbbaccddddc"; remove3ConsecutiveDuplicates(str);}} // This code contributed by Rajput-Ji # Python3 program to remove three consecutive duplicates # function to remove three consecutive duplicatesdef remove3ConsecutiveDuplicates(string): val = "" i = 0 while (i < len(string)): if (i < len(string) - 2 and string[i] * 3 == string[i:i + 3]): i += 3 else: val += string[i] i += 1 if (len(val) == len(string)): return val else: return remove3ConsecutiveDuplicates(val) # Driver codestring = "aabbbaccddddc"val = remove3ConsecutiveDuplicates(string)print(val) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to remove three consecutive// duplicatesusing System;using System.Collections.Generic; class GFG{ // function to remove three consecutive// duplicatesstatic void remove3ConsecutiveDuplicates(String str){ List<char> v = new List<char>(); for (int i = 0; i < str.Length; ++i) { v.Add(str[i]); if (v.Count > 2) { int sz = v.Count; // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.RemoveRange(sz-3,3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.Count; ++i) Console.Write(v[i]);} // Driver codepublic static void Main(String[] args){ String str = "aabbbaccddddc"; remove3ConsecutiveDuplicates(str);}} // This code has been contributed by 29AjayKumar <?php// PHP program to remove three consecutive// duplicates // function to remove three consecutive// duplicatesfunction remove3ConsecutiveDuplicates($str){ $v = array(); for ($i = 0; $i < strlen($str); ++$i) { array_push($v, $str[$i]); if (count($v) > 2) { $sz = count($v); // removing three consecutive duplicates if ($v[$sz - 1] == $v[$sz - 2] && $v[$sz - 2] == $v[$sz - 3]) { array_pop($v); array_pop($v); array_pop($v); // Removing three characters // from the string } } } // printing the string final string for ($i = 0; $i < count($v); ++$i) echo $v[$i];} // Driver code $str = "aabbbaccddddc"; remove3ConsecutiveDuplicates($str); // This code is contributed by mits?> <script>// Javascript program to remove three consecutive// duplicates // function to remove three consecutive// duplicatesfunction remove3ConsecutiveDuplicates(str){ let v = []; for (let i = 0; i < str.length; ++i) { v.push(str[i]); if (v.length > 2) { let sz = v.length; // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.pop(); v.pop(); v.pop(); // Removing three characters // from the string } } } // printing the string final string for (let i = 0; i < v.length; ++i) document.write(v[i]);} // Driver codelet str = "aabbbaccddddc";remove3ConsecutiveDuplicates(str); // This code is contributed by rag2127</script> Output: ccdc This article is contributed by Roshni Agarwal. 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. SHUBHAMSINGH10 Rajput-Ji 29AjayKumar Mithun Kumar rag2127 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher sprintf() in C Convert character array to string in C++ Naive algorithm for Pattern Searching Program to count occurrence of a given character in a string How to Append a Character to a String in C Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 26207, "s": 26179, "text": "\n06 Jul, 2021" }, { "code": null, "e": 26364, "s": 26207, "text": "Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is.Examples: " }, { "code": null, "e": 26437, "s": 26364, "text": "Input : aabbbaccddddc\nOutput :ccdc\n\nInput :aabbaccddc\nOutput :aabbaccddc" }, { "code": null, "e": 26774, "s": 26439, "text": "Explanation : We insert the characters of string one by one to vector and keep on checking the size of vector. If the size of vector is greater than 2, then we will check whether the last 3 characters of the string are same or not. If the characters are same then we will move three steps backwards in array using resize() else not. " }, { "code": null, "e": 26778, "s": 26774, "text": "C++" }, { "code": null, "e": 26783, "s": 26778, "text": "Java" }, { "code": null, "e": 26791, "s": 26783, "text": "Python3" }, { "code": null, "e": 26794, "s": 26791, "text": "C#" }, { "code": null, "e": 26798, "s": 26794, "text": "PHP" }, { "code": null, "e": 26809, "s": 26798, "text": "Javascript" }, { "code": "// C++ program to remove three consecutive// duplicates#include <bits/stdc++.h>using namespace std; // function to remove three consecutive// duplicatesvoid remove3ConsecutiveDuplicates(string str){ vector<char> v; for (int i = 0; i < str.size(); ++i) { v.push_back(str[i]); if (v.size() > 2) { int sz = v.size(); // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.resize(sz - 3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.size(); ++i) cout << v[i];} // driver codeint main(){ string str = \"aabbbaccddddc\"; remove3ConsecutiveDuplicates(str); return 0;}", "e": 27642, "s": 26809, "text": null }, { "code": "// Java program to remove three consecutive// duplicatesimport java.util.*; class GFG{ // function to remove three consecutive// duplicatesstatic void remove3ConsecutiveDuplicates(String str){ Vector<Character> v = new Vector<>(); for (int i = 0; i < str.length(); ++i) { v.add(str.charAt(i)); if (v.size() > 2) { int sz = v.size(); // removing three consecutive duplicates if (v.get(sz - 1) == v.get(sz - 2) && v.get(sz - 2) == v.get(sz - 3)) { v.setSize(sz - 3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.size(); ++i) System.out.print(v.get(i));} // Driver codepublic static void main(String[] args){ String str = \"aabbbaccddddc\"; remove3ConsecutiveDuplicates(str);}} // This code contributed by Rajput-Ji", "e": 28598, "s": 27642, "text": null }, { "code": "# Python3 program to remove three consecutive duplicates # function to remove three consecutive duplicatesdef remove3ConsecutiveDuplicates(string): val = \"\" i = 0 while (i < len(string)): if (i < len(string) - 2 and string[i] * 3 == string[i:i + 3]): i += 3 else: val += string[i] i += 1 if (len(val) == len(string)): return val else: return remove3ConsecutiveDuplicates(val) # Driver codestring = \"aabbbaccddddc\"val = remove3ConsecutiveDuplicates(string)print(val) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 29225, "s": 28598, "text": null }, { "code": "// C# program to remove three consecutive// duplicatesusing System;using System.Collections.Generic; class GFG{ // function to remove three consecutive// duplicatesstatic void remove3ConsecutiveDuplicates(String str){ List<char> v = new List<char>(); for (int i = 0; i < str.Length; ++i) { v.Add(str[i]); if (v.Count > 2) { int sz = v.Count; // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.RemoveRange(sz-3,3); // Removing three characters // from the string } } } // printing the string final string for (int i = 0; i < v.Count; ++i) Console.Write(v[i]);} // Driver codepublic static void Main(String[] args){ String str = \"aabbbaccddddc\"; remove3ConsecutiveDuplicates(str);}} // This code has been contributed by 29AjayKumar", "e": 30181, "s": 29225, "text": null }, { "code": "<?php// PHP program to remove three consecutive// duplicates // function to remove three consecutive// duplicatesfunction remove3ConsecutiveDuplicates($str){ $v = array(); for ($i = 0; $i < strlen($str); ++$i) { array_push($v, $str[$i]); if (count($v) > 2) { $sz = count($v); // removing three consecutive duplicates if ($v[$sz - 1] == $v[$sz - 2] && $v[$sz - 2] == $v[$sz - 3]) { array_pop($v); array_pop($v); array_pop($v); // Removing three characters // from the string } } } // printing the string final string for ($i = 0; $i < count($v); ++$i) echo $v[$i];} // Driver code $str = \"aabbbaccddddc\"; remove3ConsecutiveDuplicates($str); // This code is contributed by mits?>", "e": 31087, "s": 30181, "text": null }, { "code": "<script>// Javascript program to remove three consecutive// duplicates // function to remove three consecutive// duplicatesfunction remove3ConsecutiveDuplicates(str){ let v = []; for (let i = 0; i < str.length; ++i) { v.push(str[i]); if (v.length > 2) { let sz = v.length; // removing three consecutive duplicates if (v[sz - 1] == v[sz - 2] && v[sz - 2] == v[sz - 3]) { v.pop(); v.pop(); v.pop(); // Removing three characters // from the string } } } // printing the string final string for (let i = 0; i < v.length; ++i) document.write(v[i]);} // Driver codelet str = \"aabbbaccddddc\";remove3ConsecutiveDuplicates(str); // This code is contributed by rag2127</script>", "e": 31978, "s": 31087, "text": null }, { "code": null, "e": 31988, "s": 31978, "text": "Output: " }, { "code": null, "e": 31993, "s": 31988, "text": "ccdc" }, { "code": null, "e": 32416, "s": 31993, "text": "This article is contributed by Roshni Agarwal. 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": 32431, "s": 32416, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 32441, "s": 32431, "text": "Rajput-Ji" }, { "code": null, "e": 32453, "s": 32441, "text": "29AjayKumar" }, { "code": null, "e": 32466, "s": 32453, "text": "Mithun Kumar" }, { "code": null, "e": 32474, "s": 32466, "text": "rag2127" }, { "code": null, "e": 32482, "s": 32474, "text": "Strings" }, { "code": null, "e": 32490, "s": 32482, "text": "Strings" }, { "code": null, "e": 32588, "s": 32490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32633, "s": 32588, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 32678, "s": 32633, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 32695, "s": 32678, "text": "Vigenère Cipher" }, { "code": null, "e": 32710, "s": 32695, "text": "sprintf() in C" }, { "code": null, "e": 32751, "s": 32710, "text": "Convert character array to string in C++" }, { "code": null, "e": 32789, "s": 32751, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 32850, "s": 32789, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 32893, "s": 32850, "text": "How to Append a Character to a String in C" } ]
C++ STL | Set 1 (vector) | Practice | GeeksforGeeks
Implement different operations on a vector A . Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries . A query can be of five types 1. a x (Adds an element x to the vector A at the end ) 2. b (Sorts the vector A in ascending order ) 3. c (Reverses the vector A) 4. d (prints the size of the vector) 5. e (prints space separated values of the vector) 5. f (Sorts the vector A in descending order) Output: The output for each test case will be space separated integers denoting the results of each query . Constraints: 1<=T<=100 1<=Q<=100 Example: Input 2 6 a 4 a 6 a 7 b c e 4 a 55 a 11 d e Output 7 6 4 2 55 11 Explanation : For the first test case There are six queries. Queries are performed in this order 1. a 4 { Vector has 4 } 2. a 7 {vector has 7 } 3. a 6 {vector has 6} 4. b {sorts the vector in ascending order, vector now is 5 6 7} 5. c {reverse the vector } 6. e {prints the element of the vectors 7 6 4} For the sec test case There are four queries. Queries are performed in this order 1. a 55 (vector A has 55} 2. a 11 (vector A has 55 ,11} 3. d (prints the size of the vector A ie. 2 ) 4. e (prints the elements of the vector A ie 55 11) Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 tanayshah25584 months ago EASY SOLUTION: void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);} /*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());} /*reverses the vector A*/void reverse_vector(vector<int> &A){ //Your code herereverse(A.begin(), A.end());} /*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code herereturn A.size();} /*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.rbegin(),A.rend());} /*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code herefor(int i=0;i<A.size();i++){ cout<<A[i]<<" ";}} 0 gpkini20026 months ago /*You are required to complete below methods*/ /*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code here A.push_back(x);} /*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());} /*reverses the vector A*/void reverse_vector(vector<int> &A){//Your code herereverse(A.begin(),A.end());} /*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code hereA.size();} /*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.rbegin(),A.rend());} /*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code here for (auto i = A.cbegin(); i != A.cend(); ++i) cout << *i << " ";}This is my solution to the above problem:) 0 Ashu10 months ago Ashu Easy solution: c++ 0 Gurveer1 year ago Gurveer correct solution /*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);}/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());}/*reverses the vector A*/void reverse_vector(vector<int> &A){reverse(A.begin(),A.end());}/*returns the size of the vector A */int size_of_vector(vector<int> &A){return A.size();}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.begin(),A.end(),greater<int>());}/*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code herefor(int x: A ){ cout<<x <<"="" ";="" }="" }="" <="" code=""> 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.01 /*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){ A.push_back(x);}/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){sort(A.begin(), A.end());}/*reverses the vector A*/void reverse_vector(vector<int> &A){reverse(A.begin(), A.end());}/*returns the size of the vector A */int size_of_vector(vector<int> &A){return A.size();}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){sort(A.begin(), A.end(), greater<int>());}/*prints space separated elements of vector A*/void print_vector(vector<int> &A){for(int x: A){ cout << x << " ";}} 0 sagar dhankar2 years ago sagar dhankar void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);} /*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){ sort(A.begin(), A.end());//Your code here} /*reverses the vector A*/void reverse_vector(vector<int> &A){ reverse(A.begin(), A.end());//Your code here} /*returns the size of the vector A */int size_of_vector(vector<int> &A){ int x = A.size(); return x;//Your code here} bool myCmp(int a, int b){ return (a > b);} /*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){ sort(A.begin(), A.end(), myCmp);//Your code here} /*prints space separated elements of vector A*/void print_vector(vector<int> &A){ for(int i=0; i<a.size(); ++i)="" cout<<="" a[i]="" <<="" "="" ";="" your="" code="" here="" }=""> 0 penny53402 years ago penny5340 shortest sol ET= 0.01upvote me for more .https://ide.geeksforgeeks.o... 0 Yash Parmar2 years ago Yash Parmar void add_to_vector(vector<int> &v,int x){//Your code herev.push_back(x);} /*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &v){//Your code heresort(v.begin(),v.end());} /*reverses the vector A*/void reverse_vector(vector<int> &v){//Your code herereverse(v.begin(),v.end());} /*returns the size of the vector A */int size_of_vector(vector<int> &v){//Your code herereturn v.size();} /*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &v){//Your code heresort(v.begin(),v.end());reverse_vector(v);} /*prints space separated elements of vector A*/void print_vector(vector<int> &v){//Your code herefor(int i=0;i<v.size();i++){ cout<<v[i]<<"="" ";="" }="" }=""> 0 samiksha mahajan2 years ago samiksha mahajan Hi, My code fails What is wrong with my solution? The code fails - "The first test case where your code failed: Input:34a 50 e d b f b e a 650 b c b c b f e a 427 e e f c d d c c c b b b f a 23 a 70 d b e Its Correct output is:50 1 50 650 50 650 50 427 650 50 427 3 3 5 23 50 70 427 650 And Your Code's output is:50 "====================code ====================/*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);} /*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(), A.end());} /*reverses the vector A*/void reverse_vector(vector<int> &A){//Your code herereverse(A.begin(), A.end());} /*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code herereturn A.size();}bool f(int a, int b){ return a > b;}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.begin(), A.end(), f);} /*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code here//for(auto i = A.begin(); i < A.end(); i++) for(auto x: A){ cout << x << " ";}cout << endl;} 0 H_ R2 years ago H_ R can anyone tell me the time complexity of this problem.. 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": 287, "s": 238, "text": "Implement different operations on a vector A .\n " }, { "code": null, "e": 978, "s": 287, "text": "Input:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of five types \n1. a x (Adds an element x to the vector A at the end )\n2. b (Sorts the vector A in ascending order )\n3. c (Reverses the vector A)\n4. d (prints the size of the vector)\n5. e (prints space separated values of the vector)\n5. f (Sorts the vector A in descending order)\n\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:" }, { "code": null, "e": 1913, "s": 978, "text": "Input\n2\n6\na 4 a 6 a 7 b c e\n4\na 55 a 11 d e\n \nOutput\n7 6 4\n2 55 11\n\nExplanation :\nFor the first test case\nThere are six queries. Queries are performed in this order\n1. a 4 { Vector has 4 }\n2. a 7 {vector has 7 }\n3. a 6 {vector has 6}\n4. b {sorts the vector in ascending order, vector now is 5 6 7}\n5. c {reverse the vector }\n6. e {prints the element of the vectors 7 6 4}\n\nFor the sec test case \nThere are four queries. Queries are performed in this order\n1. a 55 (vector A has 55}\n2. a 11 (vector A has 55 ,11}\n3. d (prints the size of the vector A ie. 2 )\n4. e (prints the elements of the vector A ie 55 11)\n\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1915, "s": 1913, "text": "0" }, { "code": null, "e": 1941, "s": 1915, "text": "tanayshah25584 months ago" }, { "code": null, "e": 1958, "s": 1941, "text": "EASY SOLUTION: " }, { "code": null, "e": 2032, "s": 1958, "text": "void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);}" }, { "code": null, "e": 2151, "s": 2032, "text": "/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());}" }, { "code": null, "e": 2261, "s": 2151, "text": "/*reverses the vector A*/void reverse_vector(vector<int> &A){ //Your code herereverse(A.begin(), A.end());}" }, { "code": null, "e": 2368, "s": 2261, "text": "/*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code herereturn A.size();}" }, { "code": null, "e": 2492, "s": 2368, "text": "/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.rbegin(),A.rend());}" }, { "code": null, "e": 2640, "s": 2492, "text": "/*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code herefor(int i=0;i<A.size();i++){ cout<<A[i]<<\" \";}}" }, { "code": null, "e": 2642, "s": 2640, "text": "0" }, { "code": null, "e": 2665, "s": 2642, "text": "gpkini20026 months ago" }, { "code": null, "e": 2712, "s": 2665, "text": "/*You are required to complete below methods*/" }, { "code": null, "e": 2842, "s": 2712, "text": "/*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code here A.push_back(x);}" }, { "code": null, "e": 2961, "s": 2842, "text": "/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());}" }, { "code": null, "e": 3067, "s": 2961, "text": "/*reverses the vector A*/void reverse_vector(vector<int> &A){//Your code herereverse(A.begin(),A.end());}" }, { "code": null, "e": 3167, "s": 3067, "text": "/*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code hereA.size();}" }, { "code": null, "e": 3291, "s": 3167, "text": "/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.rbegin(),A.rend());}" }, { "code": null, "e": 3506, "s": 3291, "text": "/*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code here for (auto i = A.cbegin(); i != A.cend(); ++i) cout << *i << \" \";}This is my solution to the above problem:)" }, { "code": null, "e": 3508, "s": 3506, "text": "0" }, { "code": null, "e": 3526, "s": 3508, "text": "Ashu10 months ago" }, { "code": null, "e": 3531, "s": 3526, "text": "Ashu" }, { "code": null, "e": 3550, "s": 3531, "text": "Easy solution: c++" }, { "code": null, "e": 3552, "s": 3550, "text": "0" }, { "code": null, "e": 3570, "s": 3552, "text": "Gurveer1 year ago" }, { "code": null, "e": 3578, "s": 3570, "text": "Gurveer" }, { "code": null, "e": 3595, "s": 3578, "text": "correct solution" }, { "code": null, "e": 4315, "s": 3595, "text": "/*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);}/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(),A.end());}/*reverses the vector A*/void reverse_vector(vector<int> &A){reverse(A.begin(),A.end());}/*returns the size of the vector A */int size_of_vector(vector<int> &A){return A.size();}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.begin(),A.end(),greater<int>());}/*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code herefor(int x: A ){ cout<<x <<\"=\"\" \";=\"\" }=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 4317, "s": 4315, "text": "0" }, { "code": null, "e": 4343, "s": 4317, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 4359, "s": 4343, "text": "Debojyoti Sinha" }, { "code": null, "e": 4408, "s": 4359, "text": "Correct Answer.Correct AnswerExecution Time:0.01" }, { "code": null, "e": 5046, "s": 4408, "text": "/*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){ A.push_back(x);}/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){sort(A.begin(), A.end());}/*reverses the vector A*/void reverse_vector(vector<int> &A){reverse(A.begin(), A.end());}/*returns the size of the vector A */int size_of_vector(vector<int> &A){return A.size();}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){sort(A.begin(), A.end(), greater<int>());}/*prints space separated elements of vector A*/void print_vector(vector<int> &A){for(int x: A){ cout << x << \" \";}}" }, { "code": null, "e": 5048, "s": 5046, "text": "0" }, { "code": null, "e": 5073, "s": 5048, "text": "sagar dhankar2 years ago" }, { "code": null, "e": 5087, "s": 5073, "text": "sagar dhankar" }, { "code": null, "e": 5161, "s": 5087, "text": "void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);}" }, { "code": null, "e": 5285, "s": 5161, "text": "/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){ sort(A.begin(), A.end());//Your code here}" }, { "code": null, "e": 5396, "s": 5285, "text": "/*reverses the vector A*/void reverse_vector(vector<int> &A){ reverse(A.begin(), A.end());//Your code here}" }, { "code": null, "e": 5521, "s": 5396, "text": "/*returns the size of the vector A */int size_of_vector(vector<int> &A){ int x = A.size(); return x;//Your code here}" }, { "code": null, "e": 5567, "s": 5521, "text": "bool myCmp(int a, int b){ return (a > b);}" }, { "code": null, "e": 5701, "s": 5567, "text": "/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){ sort(A.begin(), A.end(), myCmp);//Your code here}" }, { "code": null, "e": 5884, "s": 5701, "text": "/*prints space separated elements of vector A*/void print_vector(vector<int> &A){ for(int i=0; i<a.size(); ++i)=\"\" cout<<=\"\" a[i]=\"\" <<=\"\" \"=\"\" \";=\"\" your=\"\" code=\"\" here=\"\" }=\"\">" }, { "code": null, "e": 5886, "s": 5884, "text": "0" }, { "code": null, "e": 5907, "s": 5886, "text": "penny53402 years ago" }, { "code": null, "e": 5917, "s": 5907, "text": "penny5340" }, { "code": null, "e": 5990, "s": 5917, "text": "shortest sol ET= 0.01upvote me for more .https://ide.geeksforgeeks.o..." }, { "code": null, "e": 5992, "s": 5990, "text": "0" }, { "code": null, "e": 6015, "s": 5992, "text": "Yash Parmar2 years ago" }, { "code": null, "e": 6027, "s": 6015, "text": "Yash Parmar" }, { "code": null, "e": 6101, "s": 6027, "text": "void add_to_vector(vector<int> &v,int x){//Your code herev.push_back(x);}" }, { "code": null, "e": 6220, "s": 6101, "text": "/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &v){//Your code heresort(v.begin(),v.end());}" }, { "code": null, "e": 6326, "s": 6220, "text": "/*reverses the vector A*/void reverse_vector(vector<int> &v){//Your code herereverse(v.begin(),v.end());}" }, { "code": null, "e": 6433, "s": 6326, "text": "/*returns the size of the vector A */int size_of_vector(vector<int> &v){//Your code herereturn v.size();}" }, { "code": null, "e": 6573, "s": 6433, "text": "/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &v){//Your code heresort(v.begin(),v.end());reverse_vector(v);}" }, { "code": null, "e": 6733, "s": 6573, "text": "/*prints space separated elements of vector A*/void print_vector(vector<int> &v){//Your code herefor(int i=0;i<v.size();i++){ cout<<v[i]<<\"=\"\" \";=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 6735, "s": 6733, "text": "0" }, { "code": null, "e": 6763, "s": 6735, "text": "samiksha mahajan2 years ago" }, { "code": null, "e": 6780, "s": 6763, "text": "samiksha mahajan" }, { "code": null, "e": 6784, "s": 6780, "text": "Hi," }, { "code": null, "e": 6798, "s": 6784, "text": "My code fails" }, { "code": null, "e": 6892, "s": 6798, "text": "What is wrong with my solution? The code fails - \"The first test case where your code failed:" }, { "code": null, "e": 6985, "s": 6892, "text": "Input:34a 50 e d b f b e a 650 b c b c b f e a 427 e e f c d d c c c b b b f a 23 a 70 d b e" }, { "code": null, "e": 7067, "s": 6985, "text": "Its Correct output is:50 1 50 650 50 650 50 427 650 50 427 3 3 5 23 50 70 427 650" }, { "code": null, "e": 7096, "s": 7067, "text": "And Your Code's output is:50" }, { "code": null, "e": 7269, "s": 7096, "text": "\"====================code ====================/*inserts an element x at the back of the vector A */void add_to_vector(vector<int> &A,int x){//Your code hereA.push_back(x);}" }, { "code": null, "e": 7389, "s": 7269, "text": "/*sort the vector A in ascending order*/void sort_vector_asc(vector<int> &A){//Your code heresort(A.begin(), A.end());}" }, { "code": null, "e": 7496, "s": 7389, "text": "/*reverses the vector A*/void reverse_vector(vector<int> &A){//Your code herereverse(A.begin(), A.end());}" }, { "code": null, "e": 7767, "s": 7496, "text": "/*returns the size of the vector A */int size_of_vector(vector<int> &A){//Your code herereturn A.size();}bool f(int a, int b){ return a > b;}/*sorts the vector A in descending order*/void sort_vector_desc(vector<int> &A){//Your code heresort(A.begin(), A.end(), f);}" }, { "code": null, "e": 7963, "s": 7767, "text": "/*prints space separated elements of vector A*/void print_vector(vector<int> &A){//Your code here//for(auto i = A.begin(); i < A.end(); i++) for(auto x: A){ cout << x << \" \";}cout << endl;}" }, { "code": null, "e": 7965, "s": 7963, "text": "0" }, { "code": null, "e": 7981, "s": 7965, "text": "H_ R2 years ago" }, { "code": null, "e": 7986, "s": 7981, "text": "H_ R" }, { "code": null, "e": 8043, "s": 7986, "text": "can anyone tell me the time complexity of this problem.." }, { "code": null, "e": 8189, "s": 8043, "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": 8225, "s": 8189, "text": " Login to access your submissions. " }, { "code": null, "e": 8235, "s": 8225, "text": "\nProblem\n" }, { "code": null, "e": 8245, "s": 8235, "text": "\nContest\n" }, { "code": null, "e": 8308, "s": 8245, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8456, "s": 8308, "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": 8664, "s": 8456, "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": 8770, "s": 8664, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
wxPython - SetFont() function in wx.MenuItem - GeeksforGeeks
09 Jun, 2020 In this article we are going to learn about SetFont() function associated with wx.MenuItem class of wxPython. SetFont() function is used to set the font associated with the menu item.It takes font as parameter which is wx.Font object. Syntax: wx.MenuItem.SetFont(self, font) Parameters: Code Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # CREATE FONT fnt = wx.Font(pointSize = 8, family = wx.FONTFAMILY_MODERN, style = wx.FONTSTYLE_ITALIC, weight = wx.FONTWEIGHT_BOLD) self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.menubar = wx.MenuBar() self.fileMenu = wx.Menu() self.item = wx.MenuItem(self.fileMenu, 1, '&Radio', helpString ="Check Help", kind = wx.ITEM_CHECK) # SET FONT FOR MENU ITEM self.item self.item.SetFont(fnt) self.item.Enable(False) self.fileMenu.Append(self.item) self.menubar.Append(self.fileMenu, '&File') self.SetMenuBar(self.menubar) self.SetSize((350, 250)) self.SetTitle('Icons and shortcuts') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output: Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n09 Jun, 2020" }, { "code": null, "e": 25900, "s": 25665, "text": "In this article we are going to learn about SetFont() function associated with wx.MenuItem class of wxPython. SetFont() function is used to set the font associated with the menu item.It takes font as parameter which is wx.Font object." }, { "code": null, "e": 25908, "s": 25900, "text": "Syntax:" }, { "code": null, "e": 25941, "s": 25908, "text": "wx.MenuItem.SetFont(self, font)\n" }, { "code": null, "e": 25953, "s": 25941, "text": "Parameters:" }, { "code": null, "e": 25967, "s": 25953, "text": "Code Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # CREATE FONT fnt = wx.Font(pointSize = 8, family = wx.FONTFAMILY_MODERN, style = wx.FONTSTYLE_ITALIC, weight = wx.FONTWEIGHT_BOLD) self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.menubar = wx.MenuBar() self.fileMenu = wx.Menu() self.item = wx.MenuItem(self.fileMenu, 1, '&Radio', helpString =\"Check Help\", kind = wx.ITEM_CHECK) # SET FONT FOR MENU ITEM self.item self.item.SetFont(fnt) self.item.Enable(False) self.fileMenu.Append(self.item) self.menubar.Append(self.fileMenu, '&File') self.SetMenuBar(self.menubar) self.SetSize((350, 250)) self.SetTitle('Icons and shortcuts') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 26972, "s": 25967, "text": null }, { "code": null, "e": 26980, "s": 26972, "text": "Output:" }, { "code": null, "e": 26991, "s": 26980, "text": "Python-gui" }, { "code": null, "e": 27007, "s": 26991, "text": "Python-wxPython" }, { "code": null, "e": 27014, "s": 27007, "text": "Python" }, { "code": null, "e": 27112, "s": 27014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27144, "s": 27112, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27186, "s": 27144, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27228, "s": 27186, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27284, "s": 27228, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27311, "s": 27284, "text": "Python Classes and Objects" }, { "code": null, "e": 27342, "s": 27311, "text": "Python | os.path.join() method" }, { "code": null, "e": 27371, "s": 27342, "text": "Create a directory in Python" }, { "code": null, "e": 27393, "s": 27371, "text": "Defaultdict in Python" }, { "code": null, "e": 27432, "s": 27393, "text": "Python | Get unique values from a list" } ]
Python heapq to find K'th smallest element in a 2D array - GeeksforGeeks
26 Dec, 2017 Given an n x n matrix and integer k. Find the k’th smallest element in the given 2D array. Examples: Input : mat = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 Output : 7th smallest element is 30 We will use similar approach like K’th Smallest/Largest Element in Unsorted Array to solve this problem. Create an empty min heap using heapq in python.Now assign first row (list) in result variable and convert result list into min heap using heapify method.Now traverse remaining row elements and push them into created min heap.Now get k’th smallest element using nsmallest(k, iterable) method of heapq module. Create an empty min heap using heapq in python. Now assign first row (list) in result variable and convert result list into min heap using heapify method. Now traverse remaining row elements and push them into created min heap. Now get k’th smallest element using nsmallest(k, iterable) method of heapq module. # Function to find K'th smallest element in # a 2D array in Pythonimport heapq def kthSmallest(input): # assign first row to result variable # and convert it into min heap result = input[0] heapq.heapify(result) # now traverse remaining rows and push # elements in min heap for row in input[1:]: for ele in row: heapq.heappush(result,ele) # get list of first k smallest element because # nsmallest(k,list) method returns first k # smallest element now print last element of # that list kSmallest = heapq.nsmallest(k,result) print (k,"th smallest element is ",kSmallest[-1]) # Driver programif __name__ == "__main__": input = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 kthSmallest(input) Output: 7th smallest element is 30 Order-Statistics Heap Matrix Python Matrix Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Insertion and Deletion in Heaps Priority Queue in Python Priority Queue using Binary Heap Difference between Min Heap and Max Heap Min Heap in Python Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7
[ { "code": null, "e": 24561, "s": 24533, "text": "\n26 Dec, 2017" }, { "code": null, "e": 24652, "s": 24561, "text": "Given an n x n matrix and integer k. Find the k’th smallest element in the given 2D array." }, { "code": null, "e": 24662, "s": 24652, "text": "Examples:" }, { "code": null, "e": 24847, "s": 24662, "text": "Input : mat = [[10, 25, 20, 40],\n [15, 45, 35, 30],\n [24, 29, 37, 48],\n [32, 33, 39, 50]]\n k = 7 \nOutput : 7th smallest element is 30\n" }, { "code": null, "e": 24952, "s": 24847, "text": "We will use similar approach like K’th Smallest/Largest Element in Unsorted Array to solve this problem." }, { "code": null, "e": 25260, "s": 24952, "text": "Create an empty min heap using heapq in python.Now assign first row (list) in result variable and convert result list into min heap using heapify method.Now traverse remaining row elements and push them into created min heap.Now get k’th smallest element using nsmallest(k, iterable) method of heapq module." }, { "code": null, "e": 25308, "s": 25260, "text": "Create an empty min heap using heapq in python." }, { "code": null, "e": 25415, "s": 25308, "text": "Now assign first row (list) in result variable and convert result list into min heap using heapify method." }, { "code": null, "e": 25488, "s": 25415, "text": "Now traverse remaining row elements and push them into created min heap." }, { "code": null, "e": 25571, "s": 25488, "text": "Now get k’th smallest element using nsmallest(k, iterable) method of heapq module." }, { "code": "# Function to find K'th smallest element in # a 2D array in Pythonimport heapq def kthSmallest(input): # assign first row to result variable # and convert it into min heap result = input[0] heapq.heapify(result) # now traverse remaining rows and push # elements in min heap for row in input[1:]: for ele in row: heapq.heappush(result,ele) # get list of first k smallest element because # nsmallest(k,list) method returns first k # smallest element now print last element of # that list kSmallest = heapq.nsmallest(k,result) print (k,\"th smallest element is \",kSmallest[-1]) # Driver programif __name__ == \"__main__\": input = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 kthSmallest(input)", "e": 26404, "s": 25571, "text": null }, { "code": null, "e": 26412, "s": 26404, "text": "Output:" }, { "code": null, "e": 26440, "s": 26412, "text": "7th smallest element is 30\n" }, { "code": null, "e": 26457, "s": 26440, "text": "Order-Statistics" }, { "code": null, "e": 26462, "s": 26457, "text": "Heap" }, { "code": null, "e": 26469, "s": 26462, "text": "Matrix" }, { "code": null, "e": 26476, "s": 26469, "text": "Python" }, { "code": null, "e": 26483, "s": 26476, "text": "Matrix" }, { "code": null, "e": 26488, "s": 26483, "text": "Heap" }, { "code": null, "e": 26586, "s": 26488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26595, "s": 26586, "text": "Comments" }, { "code": null, "e": 26608, "s": 26595, "text": "Old Comments" }, { "code": null, "e": 26640, "s": 26608, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 26665, "s": 26640, "text": "Priority Queue in Python" }, { "code": null, "e": 26698, "s": 26665, "text": "Priority Queue using Binary Heap" }, { "code": null, "e": 26739, "s": 26698, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 26758, "s": 26739, "text": "Min Heap in Python" }, { "code": null, "e": 26793, "s": 26758, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 26837, "s": 26793, "text": "Program to find largest element in an array" }, { "code": null, "e": 26873, "s": 26837, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 26935, "s": 26873, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" } ]
Java Program to create a HashMap and add key-value pairs
To create a HashMap, use the HashMap class − HashMap hm = new HashMap(); Add elements to the HashMap in the form of key-value pair − hm.put("Bag", new Integer(1100)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); The following is an example to create HashMap and add key-value pair − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Bag", new Integer(1100)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); } } Belt: 600 Wallet: 700 Bag: 1100
[ { "code": null, "e": 1107, "s": 1062, "text": "To create a HashMap, use the HashMap class −" }, { "code": null, "e": 1135, "s": 1107, "text": "HashMap hm = new HashMap();" }, { "code": null, "e": 1195, "s": 1135, "text": "Add elements to the HashMap in the form of key-value pair −" }, { "code": null, "e": 1299, "s": 1195, "text": "hm.put(\"Bag\", new Integer(1100));\nhm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));" }, { "code": null, "e": 1370, "s": 1299, "text": "The following is an example to create HashMap and add key-value pair −" }, { "code": null, "e": 1381, "s": 1370, "text": " Live Demo" }, { "code": null, "e": 2038, "s": 1381, "text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n // Put elements to the map\n hm.put(\"Bag\", new Integer(1100));\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n }\n}" }, { "code": null, "e": 2070, "s": 2038, "text": "Belt: 600\nWallet: 700\nBag: 1100" } ]
jQuery - Multiple Elements Selector
This Multiple Elements selector selects the combined results of all the specified selectors E, F or G. You can specify any number of selectors to combine into a single result. Here order of the DOM elements in the jQuery object aren't necessarily identical. Here is the simple syntax to use this selector − $('E, F, G,....') Here is the description of all the parameters used by this selector − E − Any valid selector E − Any valid selector F − Any valid selector F − Any valid selector G − Any valid selector G − Any valid selector .... .... Like any other jQuery selector, this selector also returns an array filled with the found elements. $('div, p') − selects all the elements matched by div or p. $('div, p') − selects all the elements matched by div or p. $('p strong, .myclass') − selects all elements matched by strong that are descendants of an element matched by p as well as all elements that have a class of myclass. $('p strong, .myclass') − selects all elements matched by strong that are descendants of an element matched by p as well as all elements that have a class of myclass. $('p strong, #myid') − selects a single elements matched by strong that is descendant of an element matched by p as well as element whose id is myid. $('p strong, #myid') − selects a single elements matched by strong that is descendant of an element matched by p as well as element whose id is myid. Following example would select elements with class ID big and element with ID div3 and will apply yellow color to its background − <html> <head> <title>The Selecter Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $(".big, #div3").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" id = "div1"> <p>This is first division of the DOM.</p> </div> <div class = "medium" id = "div2"> <p>This is second division of the DOM.</p> </div> <div class = "small" id = "div3"> <p>This is third division of the DOM</p> </div> </body> </html> This will produce following result − This is first division of the DOM. This is second division of the DOM. This is third division of the DOM 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2425, "s": 2322, "text": "This Multiple Elements selector selects the combined results of all the specified selectors E, F or G." }, { "code": null, "e": 2580, "s": 2425, "text": "You can specify any number of selectors to combine into a single result. Here order of the DOM elements in the jQuery object aren't necessarily identical." }, { "code": null, "e": 2629, "s": 2580, "text": "Here is the simple syntax to use this selector −" }, { "code": null, "e": 2648, "s": 2629, "text": "$('E, F, G,....')\n" }, { "code": null, "e": 2718, "s": 2648, "text": "Here is the description of all the parameters used by this selector −" }, { "code": null, "e": 2741, "s": 2718, "text": "E − Any valid selector" }, { "code": null, "e": 2764, "s": 2741, "text": "E − Any valid selector" }, { "code": null, "e": 2787, "s": 2764, "text": "F − Any valid selector" }, { "code": null, "e": 2810, "s": 2787, "text": "F − Any valid selector" }, { "code": null, "e": 2833, "s": 2810, "text": "G − Any valid selector" }, { "code": null, "e": 2856, "s": 2833, "text": "G − Any valid selector" }, { "code": null, "e": 2861, "s": 2856, "text": "...." }, { "code": null, "e": 2866, "s": 2861, "text": "...." }, { "code": null, "e": 2966, "s": 2866, "text": "Like any other jQuery selector, this selector also returns an array filled with the found elements." }, { "code": null, "e": 3026, "s": 2966, "text": "$('div, p') − selects all the elements matched by div or p." }, { "code": null, "e": 3086, "s": 3026, "text": "$('div, p') − selects all the elements matched by div or p." }, { "code": null, "e": 3253, "s": 3086, "text": "$('p strong, .myclass') − selects all elements matched by strong that are descendants of an element matched by p as well as all elements that have a class of myclass." }, { "code": null, "e": 3420, "s": 3253, "text": "$('p strong, .myclass') − selects all elements matched by strong that are descendants of an element matched by p as well as all elements that have a class of myclass." }, { "code": null, "e": 3570, "s": 3420, "text": "$('p strong, #myid') − selects a single elements matched by strong that is descendant of an element matched by p as well as element whose id is myid." }, { "code": null, "e": 3720, "s": 3570, "text": "$('p strong, #myid') − selects a single elements matched by strong that is descendant of an element matched by p as well as element whose id is myid." }, { "code": null, "e": 3851, "s": 3720, "text": "Following example would select elements with class ID big and element with ID div3 and will apply yellow color to its background −" }, { "code": null, "e": 4605, "s": 3851, "text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\".big, #div3\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <div class = \"big\" id = \"div1\">\n <p>This is first division of the DOM.</p>\n </div>\n\n <div class = \"medium\" id = \"div2\">\n <p>This is second division of the DOM.</p>\n </div>\n\n <div class = \"small\" id = \"div3\">\n <p>This is third division of the DOM</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4642, "s": 4605, "text": "This will produce following result −" }, { "code": null, "e": 4677, "s": 4642, "text": "This is first division of the DOM." }, { "code": null, "e": 4713, "s": 4677, "text": "This is second division of the DOM." }, { "code": null, "e": 4747, "s": 4713, "text": "This is third division of the DOM" }, { "code": null, "e": 4780, "s": 4747, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4794, "s": 4780, "text": " Mahesh Kumar" }, { "code": null, "e": 4829, "s": 4794, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4843, "s": 4829, "text": " Pratik Singh" }, { "code": null, "e": 4878, "s": 4843, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4895, "s": 4878, "text": " Frahaan Hussain" }, { "code": null, "e": 4928, "s": 4895, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4956, "s": 4928, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4989, "s": 4956, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5010, "s": 4989, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5042, "s": 5010, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5059, "s": 5042, "text": " Laurence Svekis" }, { "code": null, "e": 5066, "s": 5059, "text": " Print" }, { "code": null, "e": 5077, "s": 5066, "text": " Add Notes" } ]