title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Draw Multiple Rectangles in Image using Python-Opencv
17 Oct, 2021 In this article, we are going to see how to draw multiple rectangles in an image using Python and OpenCV. imread(): In the OpenCV, the cv2.imread() function is used to read an image in Python. Syntax: cv2.imread(path_of_image, flag) rectangle(): In the OpenCV, the cv2.rectangle function is used to draw a rectangle on the image in Python. Syntax: cv2.rectangle(image, starting_coordinate, ending_coordinate, color, thickness) imshow(): In the OpenCV, the cv2.imshow() function is used to display an image in Python. Syntax: cv2.imshow(window_name, image) waitKey(): In the OpenCV, the cv2.waitkey() function allows you to wait for a specific time in milliseconds. destroyAllWindows(): In the OpenCV, the destroyAllWindows() function is used to closes all the windows created using the OpenCV methods. Python3 # importing OpenCV(cv2) moduleimport cv2 # Read RGB imageimg = cv2.imread("D:\Naveen\gfg.PNG") # Draw rectangles# Red rectanglecv2.rectangle(img, (100, 560), (700, 480), (0, 0, 255), 3) # Blue rectanglecv2.rectangle(img, (650, 450), (420, 240), (255, 0, 0), 5) # Green rectanglecv2.rectangle(img, (150, 450), (380, 240), (0, 255, 0), 4) # Output img with window name as 'image'cv2.imshow('image', img) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows() Output: Picked Python-OpenCV 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": "\n17 Oct, 2021" }, { "code": null, "e": 135, "s": 28, "text": "In this article, we are going to see how to draw multiple rectangles in an image using Python and OpenCV. " }, { "code": null, "e": 222, "s": 135, "text": "imread(): In the OpenCV, the cv2.imread() function is used to read an image in Python." }, { "code": null, "e": 262, "s": 222, "text": "Syntax: cv2.imread(path_of_image, flag)" }, { "code": null, "e": 369, "s": 262, "text": "rectangle(): In the OpenCV, the cv2.rectangle function is used to draw a rectangle on the image in Python." }, { "code": null, "e": 456, "s": 369, "text": "Syntax: cv2.rectangle(image, starting_coordinate, ending_coordinate, color, thickness)" }, { "code": null, "e": 546, "s": 456, "text": "imshow(): In the OpenCV, the cv2.imshow() function is used to display an image in Python." }, { "code": null, "e": 585, "s": 546, "text": "Syntax: cv2.imshow(window_name, image)" }, { "code": null, "e": 694, "s": 585, "text": "waitKey(): In the OpenCV, the cv2.waitkey() function allows you to wait for a specific time in milliseconds." }, { "code": null, "e": 831, "s": 694, "text": "destroyAllWindows(): In the OpenCV, the destroyAllWindows() function is used to closes all the windows created using the OpenCV methods." }, { "code": null, "e": 839, "s": 831, "text": "Python3" }, { "code": "# importing OpenCV(cv2) moduleimport cv2 # Read RGB imageimg = cv2.imread(\"D:\\Naveen\\gfg.PNG\") # Draw rectangles# Red rectanglecv2.rectangle(img, (100, 560), (700, 480), (0, 0, 255), 3) # Blue rectanglecv2.rectangle(img, (650, 450), (420, 240), (255, 0, 0), 5) # Green rectanglecv2.rectangle(img, (150, 450), (380, 240), (0, 255, 0), 4) # Output img with window name as 'image'cv2.imshow('image', img) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows()", "e": 1414, "s": 839, "text": null }, { "code": null, "e": 1422, "s": 1414, "text": "Output:" }, { "code": null, "e": 1429, "s": 1422, "text": "Picked" }, { "code": null, "e": 1443, "s": 1429, "text": "Python-OpenCV" }, { "code": null, "e": 1450, "s": 1443, "text": "Python" }, { "code": null, "e": 1548, "s": 1450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1580, "s": 1548, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1607, "s": 1580, "text": "Python Classes and Objects" }, { "code": null, "e": 1628, "s": 1607, "text": "Python OOPs Concepts" }, { "code": null, "e": 1651, "s": 1628, "text": "Introduction To PYTHON" }, { "code": null, "e": 1707, "s": 1651, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1749, "s": 1707, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1780, "s": 1749, "text": "Python | os.path.join() method" }, { "code": null, "e": 1822, "s": 1780, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1861, "s": 1822, "text": "Python | Get unique values from a list" } ]
What is the Difference between Constructor and ngOnInit in AngularJS ?
24 Apr, 2020 Constructor: Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular are preferably the Dependency Injector (DI), analyzes the builder’s components and when creating a new feature by calling the new MyClass() tries to find suppliers that match the builder’s parameter types, resolve them and pass them to similar components. new MyClass(someArg); Example: var AddNumbers= (function () { function AddNumbers(x, y) { this.x = x; this.y = y; } AddNumbers.prototype.add = function () { return this.x + point.x; }; return AddNumbers;})(); var numbers = new AddNumbers(2, 4);var additionOfNumbers = numbers.add();console.log(additionOfNumbers); Output: 6 ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create a component. We have to import OnInit like this to use it (actually using OnInit is not mandatory but it is considered good). Syntax: import {Component, OnInit} from '@ angular / core'; and to use it to execute the OnInit method, we should use a section like this: Example: import { Component, OnInit } from '@angular/core'; @Component({ selector:'app-checkbox', templateUrl:'./checkbox.component.html', styleUrls: ['./checkbox.component.css']}) export class CheckboxComponent implements OnInit { constructor() { console.log('Called Constructor'); } ngOnInit() { console.log('Called ngOnInit method'); }} Output: Called Constructor Called ngOnitit method Note: Class app sales constructor () { // First called before ngOnInit () } Oninit () { // Named after the constructor and named after NgOnChanges() } Use this interaction to apply custom startup thinking after the launch of the admin property. NGOnInit is named after the indexing of the target sites for the first time, and before any of its children are tested. Only once a guide is included. Difference between ngOnInit and Constructor: We mostly use ngOnInit in every startup/announcement and avoid things to work in builders. The constructor should only be used to start class members but should not do the actual “work”. So you should use the constructor() to set Dependency Injection and not much. ngOnInit() is a better “starting point” – this is where / when component combinations are solved. We use constructor() for all the initialization/declaration. It’s better to avoid writing actual work in the constructor. The constructor() should only be used to initialize class members but shouldn’t do actual “work”. So we should use constructor() to set up Dependency Injection, Initialization of class fields, etc. ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated. Like loading data from Database — to show the user in your HTML template view. Such code should be written in ngOnInit(). Conclusion: Constructor initializes class members. ngOnInit() is a place to put the code that we need to execute at very first as soon as the class is instantiated. AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 How to bundle an Angular app for production? What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component 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": "\n24 Apr, 2020" }, { "code": null, "e": 473, "s": 28, "text": "Constructor: Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular are preferably the Dependency Injector (DI), analyzes the builder’s components and when creating a new feature by calling the new MyClass() tries to find suppliers that match the builder’s parameter types, resolve them and pass them to similar components." }, { "code": null, "e": 495, "s": 473, "text": "new MyClass(someArg);" }, { "code": null, "e": 504, "s": 495, "text": "Example:" }, { "code": "var AddNumbers= (function () { function AddNumbers(x, y) { this.x = x; this.y = y; } AddNumbers.prototype.add = function () { return this.x + point.x; }; return AddNumbers;})(); var numbers = new AddNumbers(2, 4);var additionOfNumbers = numbers.add();console.log(additionOfNumbers);", "e": 824, "s": 504, "text": null }, { "code": null, "e": 832, "s": 824, "text": "Output:" }, { "code": null, "e": 834, "s": 832, "text": "6" }, { "code": null, "e": 1054, "s": 834, "text": "ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create a component. We have to import OnInit like this to use it (actually using OnInit is not mandatory but it is considered good)." }, { "code": null, "e": 1062, "s": 1054, "text": "Syntax:" }, { "code": null, "e": 1114, "s": 1062, "text": "import {Component, OnInit} from '@ angular / core';" }, { "code": null, "e": 1193, "s": 1114, "text": "and to use it to execute the OnInit method, we should use a section like this:" }, { "code": null, "e": 1202, "s": 1193, "text": "Example:" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector:'app-checkbox', templateUrl:'./checkbox.component.html', styleUrls: ['./checkbox.component.css']}) export class CheckboxComponent implements OnInit { constructor() { console.log('Called Constructor'); } ngOnInit() { console.log('Called ngOnInit method'); }}", "e": 1572, "s": 1202, "text": null }, { "code": null, "e": 1580, "s": 1572, "text": "Output:" }, { "code": null, "e": 1622, "s": 1580, "text": "Called Constructor\nCalled ngOnitit method" }, { "code": null, "e": 1644, "s": 1622, "text": "Note: Class app sales" }, { "code": null, "e": 1698, "s": 1644, "text": "constructor () {\n// First called before ngOnInit ()\n}" }, { "code": null, "e": 1774, "s": 1698, "text": "Oninit () {\n// Named after the constructor and named after NgOnChanges()\n}\n" }, { "code": null, "e": 2019, "s": 1774, "text": "Use this interaction to apply custom startup thinking after the launch of the admin property. NGOnInit is named after the indexing of the target sites for the first time, and before any of its children are tested. Only once a guide is included." }, { "code": null, "e": 2064, "s": 2019, "text": "Difference between ngOnInit and Constructor:" }, { "code": null, "e": 2251, "s": 2064, "text": "We mostly use ngOnInit in every startup/announcement and avoid things to work in builders. The constructor should only be used to start class members but should not do the actual “work”." }, { "code": null, "e": 2427, "s": 2251, "text": "So you should use the constructor() to set Dependency Injection and not much. ngOnInit() is a better “starting point” – this is where / when component combinations are solved." }, { "code": null, "e": 2488, "s": 2427, "text": "We use constructor() for all the initialization/declaration." }, { "code": null, "e": 2549, "s": 2488, "text": "It’s better to avoid writing actual work in the constructor." }, { "code": null, "e": 2647, "s": 2549, "text": "The constructor() should only be used to initialize class members but shouldn’t do actual “work”." }, { "code": null, "e": 2747, "s": 2647, "text": "So we should use constructor() to set up Dependency Injection, Initialization of class fields, etc." }, { "code": null, "e": 2866, "s": 2747, "text": "ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated." }, { "code": null, "e": 2988, "s": 2866, "text": "Like loading data from Database — to show the user in your HTML template view. Such code should be written in ngOnInit()." }, { "code": null, "e": 3000, "s": 2988, "text": "Conclusion:" }, { "code": null, "e": 3039, "s": 3000, "text": "Constructor initializes class members." }, { "code": null, "e": 3153, "s": 3039, "text": "ngOnInit() is a place to put the code that we need to execute at very first as soon as the class is instantiated." }, { "code": null, "e": 3168, "s": 3153, "text": "AngularJS-Misc" }, { "code": null, "e": 3175, "s": 3168, "text": "Picked" }, { "code": null, "e": 3185, "s": 3175, "text": "AngularJS" }, { "code": null, "e": 3202, "s": 3185, "text": "Web Technologies" }, { "code": null, "e": 3229, "s": 3202, "text": "Web technologies Questions" }, { "code": null, "e": 3327, "s": 3229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3358, "s": 3327, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 3382, "s": 3358, "text": "Routing in Angular 9/10" }, { "code": null, "e": 3427, "s": 3382, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 3469, "s": 3427, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 3504, "s": 3469, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 3537, "s": 3504, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3599, "s": 3537, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3660, "s": 3599, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3710, "s": 3660, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Coding Guidelines in Java
24 Jan, 2022 Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner. In this article, let us understand a few coding guidelines that help to increase the readability of the program. The coding guidelines are important because most of the software cost goes towards maintenance. And also, the software is not always developed by a single developer. Therefore, maintaining a convention for writing software increases the readability of the program. A few of the guidelines are: 1. Naming Conventions: We generally follow the camel case convention in java programming. It means that all the classes and interfaces should be nouns, in mixed cases with the first letter of each internal word capitalized. All the methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized. The variables should be meaningful and one character variable names must be avoided. A constant variable is defined in the capital case. 2. Curly Braces: Curly braces are used to define the bodies of classes, methods, and loops. There are two standard formats for the usage of curly braces, either of which is used. No blank lines should be present after the opening brace or before the closing brace. A curly brace is applied at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line. For example: class Geeksforgeeks { ... Geeksforgeeks(){ // Constructor ... } int Geek(int a, float b){ ... for (int i = 0; i < Field; i++){ .... } } } Each curly brace is added on a new line, and the pair is aligned vertically. The preceding code snippet in this format would be as follows: class Geeksforgeeks { ... Geeksforgeeks() { // Constructor ... } int Geek(int a, float b) { ... for (int i = 0; i < Field; i++) { .... }...; } } 3. Indentation: The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces. All indentation must be achieved by the space character and tab characters must not exist in the resultant source file. The recognized standard for increasing readability of each line is: Apply indentation to alike items in a vertical list (such as end-of-line comments, and identifiers in declarations). Surround the binary operators (including assignment) by spaces. Follow a semicolon or comma by a space. Add a space between a keyword(“if”, “while”, “return”, “catch”, “switch”, “for”) and a succeeding parenthesis. Surplus parentheses can also help to highlight the structure of expressions (but avoid using too many nested parentheses). Insert blank lines to differentiate between the important parts of the code. Let’s implement all the above guidelines in a code: class Geeksforgeeks { private int s; private double d; Geeksforgeeks() { // Constructor s = 1; d = 3.14; } int Geek(int a, float b) { // Must initialize local variables int l = 0; float le = 1; int n = 10; l = n - 2; le = l + b * 3; for (int i = 0; i & lt; n; i++) { l = l * 2; l = l - n; } return l + a; } } 4. White Space: White spaces also play a major part in readability as follows: Operators should be surrounded by a space character. For example: The operation should be written as: a = (b + c) * d;And not as: a=(b+c)*d Reserved words of Java should be followed by white space. For example: The loop must be initialized as: while (true) {...} And not as: while(true){...} Commas should be followed by white space. For example: The functions must be initialized as: fun(a, b, c, d); And not as: fun(a, b, c, d); Colons should be surrounded by white space. For example: The case statements must be initialized as: case 100 : break; And not as: case 100:break; Semicolons in for statements should be followed by a space character. For example: The for loop must be initialized as: for (i = 0; i < n; i++) And not as: for(i=0;i<n;i++) 5. Comments: Java programs can have two types of comments. They are Implementation and Documentation. Comments should contain only the information that is relevant for reading and understanding the program. For example, information about how the package is built or in what directory it resides should not be included in the program as a comment. Implementation Comments: Implementation comments are delimited by //. Java also allows the use of /*...*/ for implementation comments. Implementation comments are used for notes about a particular implementation or for temporarily removing code. Programs can have four styles of implementation comments: block, single-line, trailing, and temporarily removing code. Block comments are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method or within methods. Block comments inside a method should be indented to the same level as the code they describe. A block comment should have a blank line before its start unless it comes immediately after the start of a compound statement. For example: // block comment on line 1 // block comment on line 2 // block comment on line 3 Single-line comments can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement. For example: a = 10; b = 20;// a single-line comment c = a * b; Trailing(very short) comments can appear on the same line of the code they describe but should be separated from the code at a far off distance. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting. For example: if (a == 2) { b = true; // special case } else { c = isPrime(x); // works only for odd } Temporarily removing code: The // delimiter can comment out a partial or a complete line. It can also be used in multiple lines to comment out entire sections of code. It is important to note that this should only be used temporarily while the code is in active development; the unused code should eventually be physically removed as it can make the source more difficult to maintain. For example: if (a > 1) { b = a; // + 1; ... } else { // b = 2; ... } Documentation Comments: Documentation comments describe Java classes, interfaces, constructors, methods, and fields. They are delimited by /**...*/. Note the double-asterisk (**) at the beginning with one comment per class, interface, or member. This comment should appear just before the declaration with no space between the comment and the code it refers to. Documentation comments can be extracted to HTML files using the javadoc tool. Javadoc of class members can be specified on a single line as follows: /** This is a java documentation comment */private int comments_; Documentation comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand. Java associates documentation comments with the first declaration after the comment. As a result, documentation comments should not be present inside a method or constructor definition block. For example: Though we can say that the above-mentioned guidelines are not definitive and they are relative, but it is always preferred to maintain the guidelines because the software is never developed by a single person and might not be maintained by the same team who has developed the software. In order to solve any bugs in the software, the deployed code must be easily readable. Following the above guidelines makes the code readable not only for the developer but also for a new person who is reading the code for the first time. nishkarshgandhi java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2022" }, { "code": null, "e": 403, "s": 28, "text": "Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner. " }, { "code": null, "e": 517, "s": 403, "text": "In this article, let us understand a few coding guidelines that help to increase the readability of the program. " }, { "code": null, "e": 783, "s": 517, "text": "The coding guidelines are important because most of the software cost goes towards maintenance. And also, the software is not always developed by a single developer. Therefore, maintaining a convention for writing software increases the readability of the program. " }, { "code": null, "e": 813, "s": 783, "text": "A few of the guidelines are: " }, { "code": null, "e": 1314, "s": 813, "text": "1. Naming Conventions: We generally follow the camel case convention in java programming. It means that all the classes and interfaces should be nouns, in mixed cases with the first letter of each internal word capitalized. All the methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized. The variables should be meaningful and one character variable names must be avoided. A constant variable is defined in the capital case." }, { "code": null, "e": 1494, "s": 1314, "text": "2. Curly Braces: Curly braces are used to define the bodies of classes, methods, and loops. There are two standard formats for the usage of curly braces, either of which is used. " }, { "code": null, "e": 1580, "s": 1494, "text": "No blank lines should be present after the opening brace or before the closing brace." }, { "code": null, "e": 1784, "s": 1580, "text": "A curly brace is applied at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line. For example:" }, { "code": null, "e": 1975, "s": 1784, "text": "class Geeksforgeeks {\n ... Geeksforgeeks(){\n // Constructor\n ...\n }\n\n int Geek(int a, float b){\n \n ... for (int i = 0; i < Field; i++){\n ....\n }\n }\n}" }, { "code": null, "e": 2115, "s": 1975, "text": "Each curly brace is added on a new line, and the pair is aligned vertically. The preceding code snippet in this format would be as follows:" }, { "code": null, "e": 2319, "s": 2115, "text": "class Geeksforgeeks \n{\n ... Geeksforgeeks()\n { // Constructor\n ...\n }\n int Geek(int a, float b)\n {\n ... for (int i = 0; i < Field; i++)\n {\n ....\n }...;\n }\n}" }, { "code": null, "e": 2616, "s": 2319, "text": "3. Indentation: The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces. All indentation must be achieved by the space character and tab characters must not exist in the resultant source file. The recognized standard for increasing readability of each line is: " }, { "code": null, "e": 2733, "s": 2616, "text": "Apply indentation to alike items in a vertical list (such as end-of-line comments, and identifiers in declarations)." }, { "code": null, "e": 2797, "s": 2733, "text": "Surround the binary operators (including assignment) by spaces." }, { "code": null, "e": 2837, "s": 2797, "text": "Follow a semicolon or comma by a space." }, { "code": null, "e": 2948, "s": 2837, "text": "Add a space between a keyword(“if”, “while”, “return”, “catch”, “switch”, “for”) and a succeeding parenthesis." }, { "code": null, "e": 3071, "s": 2948, "text": "Surplus parentheses can also help to highlight the structure of expressions (but avoid using too many nested parentheses)." }, { "code": null, "e": 3148, "s": 3071, "text": "Insert blank lines to differentiate between the important parts of the code." }, { "code": null, "e": 3200, "s": 3148, "text": "Let’s implement all the above guidelines in a code:" }, { "code": null, "e": 3635, "s": 3200, "text": "class Geeksforgeeks {\n private int s;\n private double d;\n\n Geeksforgeeks()\n { // Constructor\n s = 1;\n d = 3.14;\n }\n\n int Geek(int a, float b)\n {\n // Must initialize local variables\n int l = 0;\n float le = 1;\n int n = 10;\n l = n - 2;\n le = l + b * 3;\n\n for (int i = 0; i & lt; n; i++) {\n l = l * 2;\n l = l - n;\n }\n return l + a;\n }\n}" }, { "code": null, "e": 3715, "s": 3635, "text": "4. White Space: White spaces also play a major part in readability as follows: " }, { "code": null, "e": 3781, "s": 3715, "text": "Operators should be surrounded by a space character. For example:" }, { "code": null, "e": 3856, "s": 3781, "text": "The operation should be written as: a = (b + c) * d;And not as: a=(b+c)*d " }, { "code": null, "e": 3927, "s": 3856, "text": "Reserved words of Java should be followed by white space. For example:" }, { "code": null, "e": 4009, "s": 3927, "text": "The loop must be initialized as: while (true) {...} And not as: while(true){...} " }, { "code": null, "e": 4064, "s": 4009, "text": "Commas should be followed by white space. For example:" }, { "code": null, "e": 4149, "s": 4064, "text": "The functions must be initialized as: fun(a, b, c, d); And not as: fun(a, b, c, d); " }, { "code": null, "e": 4206, "s": 4149, "text": "Colons should be surrounded by white space. For example:" }, { "code": null, "e": 4297, "s": 4206, "text": "The case statements must be initialized as: case 100 : break; And not as: case 100:break; " }, { "code": null, "e": 4380, "s": 4297, "text": "Semicolons in for statements should be followed by a space character. For example:" }, { "code": null, "e": 4471, "s": 4380, "text": "The for loop must be initialized as: for (i = 0; i < n; i++) And not as: for(i=0;i<n;i++) " }, { "code": null, "e": 4818, "s": 4471, "text": "5. Comments: Java programs can have two types of comments. They are Implementation and Documentation. Comments should contain only the information that is relevant for reading and understanding the program. For example, information about how the package is built or in what directory it resides should not be included in the program as a comment." }, { "code": null, "e": 5183, "s": 4818, "text": "Implementation Comments: Implementation comments are delimited by //. Java also allows the use of /*...*/ for implementation comments. Implementation comments are used for notes about a particular implementation or for temporarily removing code. Programs can have four styles of implementation comments: block, single-line, trailing, and temporarily removing code." }, { "code": null, "e": 5617, "s": 5183, "text": "Block comments are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method or within methods. Block comments inside a method should be indented to the same level as the code they describe. A block comment should have a blank line before its start unless it comes immediately after the start of a compound statement. For example:" }, { "code": null, "e": 5699, "s": 5617, "text": "// block comment on line 1 // block comment on line 2 // block comment on line 3 " }, { "code": null, "e": 6028, "s": 5699, "text": "Single-line comments can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement. For example:" }, { "code": null, "e": 6080, "s": 6028, "text": "a = 10; b = 20;// a single-line comment c = a * b; " }, { "code": null, "e": 6360, "s": 6080, "text": "Trailing(very short) comments can appear on the same line of the code they describe but should be separated from the code at a far off distance. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting. For example:" }, { "code": null, "e": 6455, "s": 6360, "text": "if (a == 2) {\n b = true; // special case\n}\nelse {\n c = isPrime(x); // works only for odd\n}" }, { "code": null, "e": 6853, "s": 6455, "text": "Temporarily removing code: The // delimiter can comment out a partial or a complete line. It can also be used in multiple lines to comment out entire sections of code. It is important to note that this should only be used temporarily while the code is in active development; the unused code should eventually be physically removed as it can make the source more difficult to maintain. For example:" }, { "code": null, "e": 6910, "s": 6853, "text": "if (a > 1) {\nb = a; // + 1;\n...\n}\nelse {\n// b = 2;\n...\n}" }, { "code": null, "e": 7421, "s": 6910, "text": "Documentation Comments: Documentation comments describe Java classes, interfaces, constructors, methods, and fields. They are delimited by /**...*/. Note the double-asterisk (**) at the beginning with one comment per class, interface, or member. This comment should appear just before the declaration with no space between the comment and the code it refers to. Documentation comments can be extracted to HTML files using the javadoc tool. Javadoc of class members can be specified on a single line as follows:" }, { "code": null, "e": 7487, "s": 7421, "text": "/** This is a java documentation comment */private int comments_;" }, { "code": null, "e": 7890, "s": 7487, "text": "Documentation comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand. Java associates documentation comments with the first declaration after the comment. As a result, documentation comments should not be present inside a method or constructor definition block. For example:" }, { "code": null, "e": 8415, "s": 7890, "text": "Though we can say that the above-mentioned guidelines are not definitive and they are relative, but it is always preferred to maintain the guidelines because the software is never developed by a single person and might not be maintained by the same team who has developed the software. In order to solve any bugs in the software, the deployed code must be easily readable. Following the above guidelines makes the code readable not only for the developer but also for a new person who is reading the code for the first time." }, { "code": null, "e": 8431, "s": 8415, "text": "nishkarshgandhi" }, { "code": null, "e": 8443, "s": 8431, "text": "java-basics" }, { "code": null, "e": 8448, "s": 8443, "text": "Java" }, { "code": null, "e": 8453, "s": 8448, "text": "Java" } ]
Lexicographically smaller string by swapping at most one character pair
07 Jul, 2021 Given two strings A and B of all uppercase letters, the task is to find whether is it possible to make string A strictly lexicographically smaller than string B by swapping at most one pair of characters in A.Examples: Input: A = “AGAIN”, B = “ACTION” Output: Yes Explanation: We can make string A strictly lexicographically smaller than string B by swapping G and A (AAGIN) AAGIN is lexicographically smaller than ACTION Input: A = “APPLE” B = “AAAAAPPPLLE” Output: No Approach: Sort string A.We can find the first position where A and sorted(A) doesn’t match.We then find the letter that should be in that position and swap it with the letter in the sorted(A).If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest.Now, compare string A and string B. Sort string A. We can find the first position where A and sorted(A) doesn’t match. We then find the letter that should be in that position and swap it with the letter in the sorted(A). If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest. Now, compare string A and string B. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program check whether is// it possible to make string A// lexicographically smaller than string B #include <bits/stdc++.h>using namespace std; // Swap functionvoid swap(char& x, char& y){ char temp = x; x = y; y = temp;} // Function that finds whether is// it possible to make string A// lexicographically smaller than string Bbool IsLexicographicallySmaller( string A, string B){ // Condition if string A // is already smaller than B if (A < B) { return true; } string temp = A; // Sorting temp string sort(temp.begin(), temp.end()); int index = -1; for (int i = 0; i < A.length(); i++) { // Condition for first changed // character of string A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if string A // is already sorted if (index == -1) { return false; } int j; // Finding first changed character // from last of string A for (int i = 0; i < A.length(); i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters swap(A[index], A[j]); // Condition if string A // is smaller than B if (A < B) { return true; } else { return false; }} // Driver Codeint main(){ string A = "AGAIN"; string B = "ACTION"; if (IsLexicographicallySmaller(A, B)) { cout << "Yes" << "\n"; } else { cout << "No" << "\n"; } return 0;} // Java program check whether is// it possible to make String A// lexicographically smaller than String Bimport java.util.*; class GFG{ // Swap function static String swap(String str, int i, int j) { char[] tempArr = str.toCharArray(); char temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return String.valueOf(tempArr); } // Function that finds whether is // it possible to make String A // lexicographically smaller than String B static boolean IsLexicographicallySmaller(String A, String B) { // Condition if String A // is already smaller than B if (A.compareTo(B) < 0) { return true; } String temp = A; char p[] = temp.toCharArray(); // Sorting temp String Arrays.sort(p); temp=String.valueOf(p); int index = -1; for (int i = 0; i < A.length(); i++) { // Condition for first changed // character of String A and temp if (A.charAt(i) != temp.charAt(i)) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } int j = 0; // Finding first changed character // from last of String A for (int i = 0; i < A.length(); i++) { if (A.charAt(i) == temp.charAt(index)) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A.compareTo(B) < 0) { return true; } else { return false; } } // Driver Code public static void main(String args[]) { String A = "AGAIN"; String B = "ACTION"; if (IsLexicographicallySmaller(A, B)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by AbhiThakur # Python3 program check# it possible to make string# A lexicographically smaller# than string B # Function that finds whether is# it possible to make string A# lexicographically smaller than# string Bdef IsLexicographicallySmaller(A, B): # Condition if string A # is already smaller # than B if(A < B): return True temp = A # Sorting temp string temp = ''.join(sorted(temp)) index =- 1 for i in range(len(A)): # Condition for first # changed character of # string A and temp if(A[i] != temp[i]): index = i break # Condition if string A # is already sorted if(index == -1): return False j = 0 # Finding first changed # character from last # of string A for i in range(len(A)): if(A[i] == temp[index]): j = i A = list(A) # Swap the two characters A[index], A[j] = A[j], A[index] A = ''.join(A) # Condition if string A # is smaller than B if(A < B): return True else: return False # Driver CodeA = "AGAIN"B = "ACTION" if(IsLexicographicallySmaller(A, B)): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155 // C# program check whether is// it possible to make String A// lexicographically smaller// than String Busing System;class GFG{ // Swap functionstatic string swap(string str, int i, int j){ char[] tempArr = str.ToCharArray(); char temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return new string(tempArr);} // Function that finds whether is// it possible to make String A// lexicographically smaller than String Bstatic bool IsLexicographicallySmaller(string A, string B){ // Condition if String A // is already smaller than B if (A.CompareTo(B) < 0) { return true; } string temp = A; char []p = temp.ToCharArray(); // Sorting temp String Array.Sort(p); temp=new string(p); int index = -1; for (int i = 0; i < A.Length; i++) { // Condition for first changed // character of String A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } int j = 0; // Finding first changed character // from last of String A for (int i = 0; i < A.Length; i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A.CompareTo(B) < 0) { return true; } else { return false; }} // Driver Codepublic static void Main(string []args){ string A = "AGAIN"; string B = "ACTION"; if (IsLexicographicallySmaller(A, B)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by Rutvik_56 <script>// Javascript program check whether is// it possible to make String A// lexicographically smaller than String B // Swap functionfunction swap(str,i,j){ let tempArr = str.split(""); let temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return (tempArr).join("");} // Function that finds whether is // it possible to make String A // lexicographically smaller than String Bfunction IsLexicographicallySmaller(A, B){ // Condition if String A // is already smaller than B if (A < (B) ) { return true; } let temp = A; let p = temp.split(""); // Sorting temp String p.sort(); temp=(p).join(""); let index = -1; for (let i = 0; i < A.length; i++) { // Condition for first changed // character of String A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } let j = 0; // Finding first changed character // from last of String A for (let i = 0; i < A.length; i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A < (B) ) { return true; } else { return false; }} // Driver Codelet A = "AGAIN";let B = "ACTION"; if (IsLexicographicallySmaller(A, B)) { document.write("Yes");}else { document.write("No");} // This code is contributed by ab2127</script> Yes abhaysingh290895 Akanksha_Rai rutvik_56 avanitrachhadiya2155 ab2127 lexicographic-ordering 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 What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Check if an URL is valid or not using Regular Expression Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2021" }, { "code": null, "e": 248, "s": 28, "text": "Given two strings A and B of all uppercase letters, the task is to find whether is it possible to make string A strictly lexicographically smaller than string B by swapping at most one pair of characters in A.Examples: " }, { "code": null, "e": 501, "s": 248, "text": "Input: A = “AGAIN”, B = “ACTION” Output: Yes Explanation: We can make string A strictly lexicographically smaller than string B by swapping G and A (AAGIN) AAGIN is lexicographically smaller than ACTION Input: A = “APPLE” B = “AAAAAPPPLLE” Output: No " }, { "code": null, "e": 512, "s": 501, "text": "Approach: " }, { "code": null, "e": 853, "s": 512, "text": "Sort string A.We can find the first position where A and sorted(A) doesn’t match.We then find the letter that should be in that position and swap it with the letter in the sorted(A).If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest.Now, compare string A and string B." }, { "code": null, "e": 868, "s": 853, "text": "Sort string A." }, { "code": null, "e": 936, "s": 868, "text": "We can find the first position where A and sorted(A) doesn’t match." }, { "code": null, "e": 1038, "s": 936, "text": "We then find the letter that should be in that position and swap it with the letter in the sorted(A)." }, { "code": null, "e": 1162, "s": 1038, "text": "If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest." }, { "code": null, "e": 1198, "s": 1162, "text": "Now, compare string A and string B." }, { "code": null, "e": 1249, "s": 1198, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1253, "s": 1249, "text": "C++" }, { "code": null, "e": 1258, "s": 1253, "text": "Java" }, { "code": null, "e": 1266, "s": 1258, "text": "Python3" }, { "code": null, "e": 1269, "s": 1266, "text": "C#" }, { "code": null, "e": 1280, "s": 1269, "text": "Javascript" }, { "code": "// C++ program check whether is// it possible to make string A// lexicographically smaller than string B #include <bits/stdc++.h>using namespace std; // Swap functionvoid swap(char& x, char& y){ char temp = x; x = y; y = temp;} // Function that finds whether is// it possible to make string A// lexicographically smaller than string Bbool IsLexicographicallySmaller( string A, string B){ // Condition if string A // is already smaller than B if (A < B) { return true; } string temp = A; // Sorting temp string sort(temp.begin(), temp.end()); int index = -1; for (int i = 0; i < A.length(); i++) { // Condition for first changed // character of string A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if string A // is already sorted if (index == -1) { return false; } int j; // Finding first changed character // from last of string A for (int i = 0; i < A.length(); i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters swap(A[index], A[j]); // Condition if string A // is smaller than B if (A < B) { return true; } else { return false; }} // Driver Codeint main(){ string A = \"AGAIN\"; string B = \"ACTION\"; if (IsLexicographicallySmaller(A, B)) { cout << \"Yes\" << \"\\n\"; } else { cout << \"No\" << \"\\n\"; } return 0;}", "e": 2792, "s": 1280, "text": null }, { "code": "// Java program check whether is// it possible to make String A// lexicographically smaller than String Bimport java.util.*; class GFG{ // Swap function static String swap(String str, int i, int j) { char[] tempArr = str.toCharArray(); char temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return String.valueOf(tempArr); } // Function that finds whether is // it possible to make String A // lexicographically smaller than String B static boolean IsLexicographicallySmaller(String A, String B) { // Condition if String A // is already smaller than B if (A.compareTo(B) < 0) { return true; } String temp = A; char p[] = temp.toCharArray(); // Sorting temp String Arrays.sort(p); temp=String.valueOf(p); int index = -1; for (int i = 0; i < A.length(); i++) { // Condition for first changed // character of String A and temp if (A.charAt(i) != temp.charAt(i)) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } int j = 0; // Finding first changed character // from last of String A for (int i = 0; i < A.length(); i++) { if (A.charAt(i) == temp.charAt(index)) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A.compareTo(B) < 0) { return true; } else { return false; } } // Driver Code public static void main(String args[]) { String A = \"AGAIN\"; String B = \"ACTION\"; if (IsLexicographicallySmaller(A, B)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by AbhiThakur", "e": 4890, "s": 2792, "text": null }, { "code": "# Python3 program check# it possible to make string# A lexicographically smaller# than string B # Function that finds whether is# it possible to make string A# lexicographically smaller than# string Bdef IsLexicographicallySmaller(A, B): # Condition if string A # is already smaller # than B if(A < B): return True temp = A # Sorting temp string temp = ''.join(sorted(temp)) index =- 1 for i in range(len(A)): # Condition for first # changed character of # string A and temp if(A[i] != temp[i]): index = i break # Condition if string A # is already sorted if(index == -1): return False j = 0 # Finding first changed # character from last # of string A for i in range(len(A)): if(A[i] == temp[index]): j = i A = list(A) # Swap the two characters A[index], A[j] = A[j], A[index] A = ''.join(A) # Condition if string A # is smaller than B if(A < B): return True else: return False # Driver CodeA = \"AGAIN\"B = \"ACTION\" if(IsLexicographicallySmaller(A, B)): print(\"Yes\")else: print(\"No\") # This code is contributed by avanitrachhadiya2155", "e": 6130, "s": 4890, "text": null }, { "code": "// C# program check whether is// it possible to make String A// lexicographically smaller// than String Busing System;class GFG{ // Swap functionstatic string swap(string str, int i, int j){ char[] tempArr = str.ToCharArray(); char temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return new string(tempArr);} // Function that finds whether is// it possible to make String A// lexicographically smaller than String Bstatic bool IsLexicographicallySmaller(string A, string B){ // Condition if String A // is already smaller than B if (A.CompareTo(B) < 0) { return true; } string temp = A; char []p = temp.ToCharArray(); // Sorting temp String Array.Sort(p); temp=new string(p); int index = -1; for (int i = 0; i < A.Length; i++) { // Condition for first changed // character of String A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } int j = 0; // Finding first changed character // from last of String A for (int i = 0; i < A.Length; i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A.CompareTo(B) < 0) { return true; } else { return false; }} // Driver Codepublic static void Main(string []args){ string A = \"AGAIN\"; string B = \"ACTION\"; if (IsLexicographicallySmaller(A, B)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by Rutvik_56", "e": 7777, "s": 6130, "text": null }, { "code": "<script>// Javascript program check whether is// it possible to make String A// lexicographically smaller than String B // Swap functionfunction swap(str,i,j){ let tempArr = str.split(\"\"); let temp = tempArr[i]; tempArr[i] = tempArr[j]; tempArr[j] = temp; return (tempArr).join(\"\");} // Function that finds whether is // it possible to make String A // lexicographically smaller than String Bfunction IsLexicographicallySmaller(A, B){ // Condition if String A // is already smaller than B if (A < (B) ) { return true; } let temp = A; let p = temp.split(\"\"); // Sorting temp String p.sort(); temp=(p).join(\"\"); let index = -1; for (let i = 0; i < A.length; i++) { // Condition for first changed // character of String A and temp if (A[i] != temp[i]) { index = i; break; } } // Condition if String A // is already sorted if (index == -1) { return false; } let j = 0; // Finding first changed character // from last of String A for (let i = 0; i < A.length; i++) { if (A[i] == temp[index]) j = i; } // Swap the two characters A = swap(A, index, j); // Condition if String A // is smaller than B if (A < (B) ) { return true; } else { return false; }} // Driver Codelet A = \"AGAIN\";let B = \"ACTION\"; if (IsLexicographicallySmaller(A, B)) { document.write(\"Yes\");}else { document.write(\"No\");} // This code is contributed by ab2127</script>", "e": 9546, "s": 7777, "text": null }, { "code": null, "e": 9550, "s": 9546, "text": "Yes" }, { "code": null, "e": 9569, "s": 9552, "text": "abhaysingh290895" }, { "code": null, "e": 9582, "s": 9569, "text": "Akanksha_Rai" }, { "code": null, "e": 9592, "s": 9582, "text": "rutvik_56" }, { "code": null, "e": 9613, "s": 9592, "text": "avanitrachhadiya2155" }, { "code": null, "e": 9620, "s": 9613, "text": "ab2127" }, { "code": null, "e": 9643, "s": 9620, "text": "lexicographic-ordering" }, { "code": null, "e": 9651, "s": 9643, "text": "Strings" }, { "code": null, "e": 9659, "s": 9651, "text": "Strings" }, { "code": null, "e": 9757, "s": 9659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9802, "s": 9757, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 9866, "s": 9802, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9911, "s": 9866, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 9946, "s": 9911, "text": "Print all subsequences of a string" }, { "code": null, "e": 10011, "s": 9946, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 10040, "s": 10011, "text": "String class in Java | Set 1" }, { "code": null, "e": 10101, "s": 10040, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 10153, "s": 10101, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 10210, "s": 10153, "text": "Check if an URL is valid or not using Regular Expression" } ]
Stream mapToInt() in Java with examples
06 Dec, 2018 Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output. Syntax : IntStream mapToInt(ToIntFunction<? super T> mapper) Where, IntStream is a sequence of primitive int-valued elements and T is the type of stream elements. mapper is a stateless function which is applied to each element and the function returns the new stream. Example 1 : mapToInt() with operation of printing the stream element if divisible by 3. // Java code for Stream mapToInt// (ToIntFunction mapper) to get a// IntStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("3", "6", "8", "14", "15"); // Using Stream mapToInt(ToIntFunction mapper) // and displaying the corresponding IntStream list.stream().mapToInt(num -> Integer.parseInt(num)) .filter(num -> num % 3 == 0) .forEach(System.out::println); }} Output : 3 6 15 Example 2 : mapToInt() to return IntStream after performing operation of mapping string with its length. // Java code for Stream mapToInt// (ToIntFunction mapper) to get a// IntStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("Geeks", "for", "gfg", "GeeksforGeeks", "GeeksQuiz"); // Using Stream mapToInt(ToIntFunction mapper) // and displaying the corresponding IntStream // which contains length of each element in // given Stream list.stream().mapToInt(str -> str.length()).forEach(System.out::println); }} Output : 5 3 3 13 9 Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 202, "s": 54, "text": "Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream." }, { "code": null, "e": 440, "s": 202, "text": "Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output." }, { "code": null, "e": 449, "s": 440, "text": "Syntax :" }, { "code": null, "e": 713, "s": 449, "text": "IntStream mapToInt(ToIntFunction<? super T> mapper)\n\nWhere, IntStream is a sequence of primitive \nint-valued elements and T is the type \nof stream elements. mapper is a stateless function \nwhich is applied to each element and the function\nreturns the new stream.\n" }, { "code": null, "e": 801, "s": 713, "text": "Example 1 : mapToInt() with operation of printing the stream element if divisible by 3." }, { "code": "// Java code for Stream mapToInt// (ToIntFunction mapper) to get a// IntStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"3\", \"6\", \"8\", \"14\", \"15\"); // Using Stream mapToInt(ToIntFunction mapper) // and displaying the corresponding IntStream list.stream().mapToInt(num -> Integer.parseInt(num)) .filter(num -> num % 3 == 0) .forEach(System.out::println); }}", "e": 1471, "s": 801, "text": null }, { "code": null, "e": 1480, "s": 1471, "text": "Output :" }, { "code": null, "e": 1488, "s": 1480, "text": "3\n6\n15\n" }, { "code": null, "e": 1593, "s": 1488, "text": "Example 2 : mapToInt() to return IntStream after performing operation of mapping string with its length." }, { "code": "// Java code for Stream mapToInt// (ToIntFunction mapper) to get a// IntStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"Geeks\", \"for\", \"gfg\", \"GeeksforGeeks\", \"GeeksQuiz\"); // Using Stream mapToInt(ToIntFunction mapper) // and displaying the corresponding IntStream // which contains length of each element in // given Stream list.stream().mapToInt(str -> str.length()).forEach(System.out::println); }}", "e": 2281, "s": 1593, "text": null }, { "code": null, "e": 2290, "s": 2281, "text": "Output :" }, { "code": null, "e": 2302, "s": 2290, "text": "5\n3\n3\n13\n9\n" }, { "code": null, "e": 2322, "s": 2302, "text": "Java - util package" }, { "code": null, "e": 2337, "s": 2322, "text": "Java-Functions" }, { "code": null, "e": 2349, "s": 2337, "text": "java-stream" }, { "code": null, "e": 2371, "s": 2349, "text": "Java-Stream interface" }, { "code": null, "e": 2376, "s": 2371, "text": "Java" }, { "code": null, "e": 2381, "s": 2376, "text": "Java" }, { "code": null, "e": 2479, "s": 2381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2530, "s": 2479, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2561, "s": 2530, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2580, "s": 2561, "text": "Interfaces in Java" }, { "code": null, "e": 2610, "s": 2580, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2628, "s": 2610, "text": "ArrayList in Java" }, { "code": null, "e": 2648, "s": 2628, "text": "Collections in Java" }, { "code": null, "e": 2680, "s": 2648, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2704, "s": 2680, "text": "Singleton Class in Java" }, { "code": null, "e": 2716, "s": 2704, "text": "Set in Java" } ]
How to Deploy Django application on Heroku ?
05 Sep, 2020 Django is an MVT web framework used to build web applications. It is robust, simple, and helps web developers to write clean, efficient, and powerful code. In this article, we will learn how to deploy a Django project on Heroku in simple steps. For this, a Django project should be ready, visit the following link to prepare one:https://www.geeksforgeeks.org/django-tutorial/ Django Postgres installed Requirements.txt file: Create requirements.txt file in the same directory as your manage.py. Run the following command in the console with the virtual environment activated: (myvenv) $ pip install dj-database-url gunicorn whitenoise (myvenv) $ pip freeze > requirements.txt Check your requirements.txt. It will be updated with the packages currently installed in your project. Procfile: Create a file named Procfile in the same directory as manage.py. you will see the Heroku logo as Procfile’s icon. Add the following line to it: web: gunicorn <project_name>.wsgi --log-file - Here project name will be the name of the folder in which your settings.py is present. Procfile explicitly declares what command should be executed to start your app. Runtime.txt file: Create runtime.txt file in the same directory as your manage.py. Add the python version you want to use for your web app: python-3.7.1 Settings.py: Modify your settings.py as per the instructions below: 1.Set debug as False. DEBUG = False 2. Modify allowed hosts. ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] 3. To disable Django’s static file handling and allow WhiteNoise to take over add ‘nostatic’ to the top of your ‘INSTALLED_APPS’ list. INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', # ... ] 4. Add WhiteNoise to the MIDDLEWARE list. The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ... ] 5. Update your database settings. import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<database_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) 6. To serve files directly from their original locations (usually in STATICFILES_DIRS or app static subdirectories) without needing to be collected into STATIC_ROOT by the collectstatic command; set WHITENOISE_USE_FINDERS to True. WHITENOISE_USE_FINDERS = True 7. WhiteNoise comes with a storage backend that automatically takes care of compressing your files and creating unique names for each version so they can safely be cached forever. To use it, just add this to your settings.py: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Final modified Contents of settings.py: import dj_database_url ... DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', #... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #... ] ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<database_name>', 'USER': '<username>', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '', } } WHITENOISE_USE_FINDERS = True ... db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Heroku account 1. Install your Heroku toolbelt which you can find here: https://toolbelt.heroku.com/ 2. Authenticate your Heroku account either running the below command in cmd or gitbash $heroku login Here the directory of the project(resume) to be deployed is active Sometimes the cmd or git bash may freeze at certain commands. Just use CTRL+C to come out of it. 3. Commit any changes on git before deploying. $ git status $ git add -A . $ git commit -m "additional files and changes for Heroku" 4. Pick your application name which will be displayed on the domain name– [your app’s name].herokuapp.com and create the application using below command: $ heroku create <your_app's_name> 5. Debugging: If collectstatic failed during a build, a traceback was provided that will be helpful in diagnosing the problem. If you need additional information about the environment collectstatic was run in, use the DEBUG_COLLECTSTATIC configuration. $ heroku config:set DEBUG_COLLECTSTATIC=1 6. Disabling Collectstatic: Sometimes, you may not want Heroku to run collectstatic on your behalf. You can disable the collectstatic build step with the DISABLE_COLLECTSTATIC configuration: $heroku config:set DISABLE_COLLECTSTATIC=1 7. Finally, do a simple git push to deploy our application: $ git push heroku master 8. When we deployed to Heroku, we created a new database and it’s empty. We need to run the migrate and createsuperuser commands. $ heroku run python manage.py migrate $ heroku run python manage.py createsuperuser The command prompt will ask you to choose a username and a password again. These will be your login details on your live website’s admin page. 9. To open your site run: $ heroku open Resolving Errors In case you see application error on your website run: $heroku logs --tail It displays recent logs and leaves the session open for real-time logs to stream in. By viewing a live stream of logs from your app, you can gain insight into the behavior of your live application and debug current problems. When you are done, press Ctrl+C to return to the prompt. Heroku Cloud Python Django Python Web Technologies 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() 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": 52, "s": 24, "text": "\n05 Sep, 2020" }, { "code": null, "e": 428, "s": 52, "text": "Django is an MVT web framework used to build web applications. It is robust, simple, and helps web developers to write clean, efficient, and powerful code. In this article, we will learn how to deploy a Django project on Heroku in simple steps. For this, a Django project should be ready, visit the following link to prepare one:https://www.geeksforgeeks.org/django-tutorial/" }, { "code": null, "e": 435, "s": 428, "text": "Django" }, { "code": null, "e": 454, "s": 435, "text": "Postgres installed" }, { "code": null, "e": 630, "s": 454, "text": "Requirements.txt file: Create requirements.txt file in the same directory as your manage.py. Run the following command in the console with the virtual environment activated: " }, { "code": null, "e": 691, "s": 630, "text": " (myvenv) $ pip install dj-database-url gunicorn whitenoise\n" }, { "code": null, "e": 734, "s": 691, "text": " (myvenv) $ pip freeze > requirements.txt\n" }, { "code": null, "e": 837, "s": 734, "text": "Check your requirements.txt. It will be updated with the packages currently installed in your project." }, { "code": null, "e": 993, "s": 837, "text": "Procfile: Create a file named Procfile in the same directory as manage.py. you will see the Heroku logo as Procfile’s icon. Add the following line to it:" }, { "code": null, "e": 1041, "s": 993, "text": "web: gunicorn <project_name>.wsgi --log-file -\n" }, { "code": null, "e": 1208, "s": 1041, "text": "Here project name will be the name of the folder in which your settings.py is present. Procfile explicitly declares what command should be executed to start your app." }, { "code": null, "e": 1348, "s": 1208, "text": "Runtime.txt file: Create runtime.txt file in the same directory as your manage.py. Add the python version you want to use for your web app:" }, { "code": null, "e": 1363, "s": 1348, "text": "python-3.7.1 \n" }, { "code": null, "e": 1431, "s": 1363, "text": "Settings.py: Modify your settings.py as per the instructions below:" }, { "code": null, "e": 1453, "s": 1431, "text": "1.Set debug as False." }, { "code": null, "e": 1468, "s": 1453, "text": "DEBUG = False\n" }, { "code": null, "e": 1493, "s": 1468, "text": "2. Modify allowed hosts." }, { "code": null, "e": 1542, "s": 1493, "text": "ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']\n" }, { "code": null, "e": 1677, "s": 1542, "text": "3. To disable Django’s static file handling and allow WhiteNoise to take over add ‘nostatic’ to the top of your ‘INSTALLED_APPS’ list." }, { "code": null, "e": 1780, "s": 1677, "text": "INSTALLED_APPS = [\n 'whitenoise.runserver_nostatic',\n 'django.contrib.staticfiles',\n # ...\n]\n" }, { "code": null, "e": 1965, "s": 1780, "text": "4. Add WhiteNoise to the MIDDLEWARE list. The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware:" }, { "code": null, "e": 2087, "s": 1965, "text": "MIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n # ...\n]\n" }, { "code": null, "e": 2122, "s": 2087, "text": "5. Update your database settings." }, { "code": null, "e": 2492, "s": 2122, "text": "import dj_database_url\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': '<database_name>',\n 'USER': '<user_name>',\n 'PASSWORD': '<password>',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\ndb_from_env = dj_database_url.config(conn_max_age=500)\nDATABASES['default'].update(db_from_env)\n" }, { "code": null, "e": 2724, "s": 2492, "text": "6. To serve files directly from their original locations (usually in STATICFILES_DIRS or app static subdirectories) without needing to be collected into STATIC_ROOT by the collectstatic command; set WHITENOISE_USE_FINDERS to True." }, { "code": null, "e": 2757, "s": 2724, "text": "WHITENOISE_USE_FINDERS = True\n\n\n" }, { "code": null, "e": 2983, "s": 2757, "text": "7. WhiteNoise comes with a storage backend that automatically takes care of compressing your files and creating unique names for each version so they can safely be cached forever. To use it, just add this to your settings.py:" }, { "code": null, "e": 3066, "s": 2983, "text": "STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n\n" }, { "code": null, "e": 3106, "s": 3066, "text": "Final modified Contents of settings.py:" }, { "code": null, "e": 3888, "s": 3106, "text": "import dj_database_url\n\n\n...\n\n\n\nDEBUG = False\n\nALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']\n\nINSTALLED_APPS = [\n 'whitenoise.runserver_nostatic',\n \n #...\n \n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n \n #...\n]\n\n\n...\n\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': '<database_name>',\n 'USER': '<username>',\n 'PASSWORD': '<password>',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\nWHITENOISE_USE_FINDERS = True\n\n\n...\n\n\n\ndb_from_env = dj_database_url.config(conn_max_age=500)\nDATABASES['default'].update(db_from_env)\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n" }, { "code": null, "e": 3903, "s": 3888, "text": "Heroku account" }, { "code": null, "e": 3989, "s": 3903, "text": "1. Install your Heroku toolbelt which you can find here: https://toolbelt.heroku.com/" }, { "code": null, "e": 4076, "s": 3989, "text": "2. Authenticate your Heroku account either running the below command in cmd or gitbash" }, { "code": null, "e": 4091, "s": 4076, "text": "$heroku login\n" }, { "code": null, "e": 4160, "s": 4091, "text": "Here the directory of the project(resume) to be deployed is active" }, { "code": null, "e": 4257, "s": 4160, "text": "Sometimes the cmd or git bash may freeze at certain commands. Just use CTRL+C to come out of it." }, { "code": null, "e": 4304, "s": 4257, "text": "3. Commit any changes on git before deploying." }, { "code": null, "e": 4391, "s": 4304, "text": "$ git status\n$ git add -A .\n$ git commit -m \"additional files and changes for Heroku\"\n" }, { "code": null, "e": 4545, "s": 4391, "text": "4. Pick your application name which will be displayed on the domain name– [your app’s name].herokuapp.com and create the application using below command:" }, { "code": null, "e": 4580, "s": 4545, "text": "$ heroku create <your_app's_name>\n" }, { "code": null, "e": 4833, "s": 4580, "text": "5. Debugging: If collectstatic failed during a build, a traceback was provided that will be helpful in diagnosing the problem. If you need additional information about the environment collectstatic was run in, use the DEBUG_COLLECTSTATIC configuration." }, { "code": null, "e": 4876, "s": 4833, "text": "$ heroku config:set DEBUG_COLLECTSTATIC=1\n" }, { "code": null, "e": 5067, "s": 4876, "text": "6. Disabling Collectstatic: Sometimes, you may not want Heroku to run collectstatic on your behalf. You can disable the collectstatic build step with the DISABLE_COLLECTSTATIC configuration:" }, { "code": null, "e": 5111, "s": 5067, "text": "$heroku config:set DISABLE_COLLECTSTATIC=1\n" }, { "code": null, "e": 5171, "s": 5111, "text": "7. Finally, do a simple git push to deploy our application:" }, { "code": null, "e": 5197, "s": 5171, "text": "$ git push heroku master\n" }, { "code": null, "e": 5327, "s": 5197, "text": "8. When we deployed to Heroku, we created a new database and it’s empty. We need to run the migrate and createsuperuser commands." }, { "code": null, "e": 5366, "s": 5327, "text": "$ heroku run python manage.py migrate\n" }, { "code": null, "e": 5415, "s": 5366, "text": "$ heroku run python manage.py createsuperuser\n\n\n" }, { "code": null, "e": 5558, "s": 5415, "text": "The command prompt will ask you to choose a username and a password again. These will be your login details on your live website’s admin page." }, { "code": null, "e": 5584, "s": 5558, "text": "9. To open your site run:" }, { "code": null, "e": 5599, "s": 5584, "text": "$ heroku open\n" }, { "code": null, "e": 5616, "s": 5599, "text": "Resolving Errors" }, { "code": null, "e": 5671, "s": 5616, "text": "In case you see application error on your website run:" }, { "code": null, "e": 5692, "s": 5671, "text": "$heroku logs --tail\n" }, { "code": null, "e": 5974, "s": 5692, "text": "It displays recent logs and leaves the session open for real-time logs to stream in. By viewing a live stream of logs from your app, you can gain insight into the behavior of your live application and debug current problems. When you are done, press Ctrl+C to return to the prompt." }, { "code": null, "e": 5987, "s": 5974, "text": "Heroku Cloud" }, { "code": null, "e": 6001, "s": 5987, "text": "Python Django" }, { "code": null, "e": 6008, "s": 6001, "text": "Python" }, { "code": null, "e": 6025, "s": 6008, "text": "Web Technologies" }, { "code": null, "e": 6123, "s": 6025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6141, "s": 6123, "text": "Python Dictionary" }, { "code": null, "e": 6183, "s": 6141, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6205, "s": 6183, "text": "Enumerate() in Python" }, { "code": null, "e": 6240, "s": 6205, "text": "Read a file line by line in Python" }, { "code": null, "e": 6266, "s": 6240, "text": "Python String | replace()" }, { "code": null, "e": 6299, "s": 6266, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6361, "s": 6299, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6422, "s": 6361, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6472, "s": 6422, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to return custom JSON in Django REST Framework ?
27 Apr, 2021 In this article, we will create class-based views and combine this with the serializer class to return JSON representation for each HTTP request. For our class-based views, we will make use of a set of generic views, which help to achieve minimum lines code. Generic Classes and Viewsets HTTP requests to interact with relationship resources We will take advantage of generic class views to implement get, post, delete, put, and patch methods. For this, we need to make use of two generic class views from the rest_framework.generics module. They are: ListCreateAPIView RetrieveUpdateDestroyAPIView The ListCreateAPIView class view implements the get method (retrieves a listing of a queryset) and post method (creates a model instance). And, the RetrieveUpdateDestroyAPIView class view implements get (retrieve a model instance), delete (delete a model instance), put (completely update a model instance), and patch (partially update a model instance). In the Django REST framework, these two generic views are implemented as mixin classes. The ListCreateAPIView uses ListModelMixin and CreateModelMixin from rest_framework.mixins module and GenericAPIView from rest_framework.generics module. Let’s look at its declaration. Python3 class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): The RetrieveUpdateDestroyAPIView uses RetrieveModelMixin, UpdateModelMixin and DestroyModelMixin from rest_framework.mixins module and GenericAPIView from rest_framework.generics module. Let’s look at its declaration. Python3 class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView): Now, let’s get back to our RESTFul web service code and create the required set of Django class-based views. You can open the restpi\robots\views.py Python file and replace it with the below code. Python3 from django.shortcuts import render from rest_framework import genericsfrom rest_framework.response import Responsefrom rest_framework.reverse import reverse from robots.models import RobotCategoryfrom robots.models import Manufacturerfrom robots.models import Robot from robots.serializers import RobotCategorySerializerfrom robots.serializers import ManufacturerSerializerfrom robots.serializers import RobotSerializer class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) class RobotCategoryList(generics.ListCreateAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer class RobotCategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-detail' class ManufacturerList(generics.ListCreateAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-list' class ManufacturerDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-detail' class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail' Here the RobotCategoryList, ManufacturerList, and RobotList are the subclasses of generics.ListCreateAPIView; the RobotCategoryDetail, ManufacturerDetail, and RobotDetail are the subclasses of generics.RetrieveUpdateDestroyAPIView. Every subclass has a queryset attribute, serializer_class attribute, and a name attribute. The queryset attribute stores all the retrieved objects, the serializer_class attribute stores the serializer class, and the name attribute is used to identify each view. Apart from class-based views, you can notice an ApiRoot class, which is a subclass of the rest_framework.generics.GenericAPIView. Python3 class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) The ApiRoot class creates an end-point for the root of our RESTful web service that facilitates browsing the resource collection. The get method defines in this class returns a Response object that has the descriptive name and its URL. Here, it returns descriptive name and URL for robot categories list, manufacturers list, and robots list. Next, we need to specify the URL pattern in the regular expression to run a specific method for a class-based view defined in the views.py Python file. The client HTTP request has to match with this regular expression to run the methods in the views.py file. You can create the urls.py file in the restapi/robots and add the below code. Python3 from django.conf.urls import urlfrom robots import views urlpatterns = [ url(r'^robot-categories/$', views.RobotCategoryList.as_view(), name=views.RobotCategoryList.name), url(r'^robot-categories/(?P<pk>[0-9]+)$', views.RobotCategoryDetail.as_view(), name=views.RobotCategoryDetail.name), url(r'^manufacturers/$', views.ManufacturerList.as_view(), name=views.ManufacturerList.name), url(r'^manufacturers/(?P<pk>[0-9]+)$', views.ManufacturerDetail.as_view(), name=views.ManufacturerDetail.name), url(r'^robots/$', views.RobotList.as_view(), name=views.RobotList.name), url(r'^robots/(?P<pk>[0-9]+)$', views.RobotDetail.as_view(), name=views.RobotDetail.name), url(r'^$', views.ApiRoot.as_view(), name=views.ApiRoot.name),] As a final step, we need to define the root URL configuration. You can open the restapi/restapi/urls.py Python file and replace it with the below code: Python3 from django.conf.urls import url, include urlpatterns = [ url(r'^', include('robots.urls')),] It is time to test our code by composing and sending the various HTTP requests. Here, we will take advantage of both the HTTPie command and the CURL command. Let’s compose and send an HTTP Post request to create a new robot category. The HTTPie command is: http POST :8000/robot-categories/ name=”Articulated Robots” notes=”Flexibility, dexterity, and reach make articulated robots ideally suited for tasks that span non-parallel planes” Output: Robot Category Post Request (HTTPie) Let’s create another robot category using the curl command. curl -iX POST -H “Content-Type: application/json” -d “{\”name\”:\”SCARA Robots\”, \”notes\”:\”A Selective Compliance Articulated Robot Arm (SCARA) is a good and cost-effective choice for performing operations between two parallel planes\”}” localhost:8000/robot-categories/ Output: Robot Category POST request (cURL) Let’s compose a GET request to retrieve all robot categories. The HTTPie command is: http :8000/robot-categories/ Output: Robot Category GET request (HTTPie utility command) The equivalent curl command is curl -iX GET localhost:8000/robot-categories/ Output: GET request (cURL) The HTTPie command to retrieve a robot category is: http :8000/robot-categories/1 Output: GET request (single category) The equivalent curl command is: curl -iX GET localhost:8000/robot-categories/1 Let’s compose and send an HTTP POST request to create a manufacturer. The HTTPie command is: http :8000/manufacturers/ name=”FANUC Global” rating=4 notes=”The automation specialist and industrial robot manufacturer” Output: HTTP/1.1 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Length: 219 Content-Type: application/json Date: Mon, 16 Nov 2020 06:36:12 GMT Location: http://localhost:8000/manufacturers/1 Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.5 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { “entry_date”: “2020-11-16T06:36:12.449074Z”, “robots”: [], “name”: “FANUC Global”, “notes”: “The automation specialist and industrial robot manufacturer”, “pk”: 1, “rating”: 4, “url”: “http://localhost:8000/manufacturers/1” } Let’s create another manufacturer using the curl command. curl -iX POST -H “Content-Type: application/json” -d “{\”name\”:\”ABB\”, \”rating\”:5, \”notes\”:\”Focused in Electrification, Industrial Automation, Robotics, Discrete Automation and Motion\”}” localhost:8000/manufacturers/ Output: HTTP/1.1 201 Created Date: Mon, 16 Nov 2020 06:49:43 GMT Server: WSGIServer/0.2 CPython/3.7.5 Content-Type: application/json Location: http://localhost:8000/manufacturers/2 Vary: Accept, Cookie Allow: GET, POST, HEAD, OPTIONS X-Frame-Options: DENY Content-Length: 242 X-Content-Type-Options: nosniff Referrer-Policy: same-origin {“url”:”http://localhost:8000/manufacturers/2′′,”pk”:2,”name”:”ABB”,”rating”:5, “notes”:”Focused in Electrification, Industrial Automation, Robotics, Discrete Automation and Motion”,”entry_date”:”2020-11-16T06:49:43.108992Z”,”robots”:[]} Let’s compose a request to retrieve a manufacturer. The HTTPie command is: http :8000/manufacturers/2 Output: Retrieve a single manufacturer The equivalent curl command is: curl -iX GET localhost:8000/manufacturers/2 We have populated the robot category and manufacturer details. Now, let’s compose and send a POST request to add robot details. The HTTPie command is http POST :8000/robots/ name=”FANUC M-710ic/50′′ robot_category=”Articulated Robots” currency=”USD” price=37000 manufacturer=”FANUC Global” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Axes 6, Payload 50 KG, Reach 2050 MM” Output: Robot Entry (HTTP Utility Pie command) Let’s compose a curl command to create a new entry. curl -iX POST -H “Content-Type: application/json” -d “{\”name\”:\”SR-3iA\”, \”robot_category\”:\”SCARA Robots\”, \”currency\”:\”USD\”, \”price\”:37000, \”manufacturer\”:\”FANUC Global\”, \”manufacturing_date\”:\”2019-10-12 00:00:00.000000+00:00\”, \”add_details\”:\”Axis 4, Payload 3 KG, Reach 400 MM\”}” localhost:8000/robots/ Output: Let’s add a few more entries in Robot. The HTTPie commands are: http POST :8000/robots/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=14500 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00.000000+00:00′′ add_details=”Axes 6, Payload 3 KG, Reach 0.58m” http POST :8000/robots/ name=”IRB 910SC” robot_category=”SCARA Robots” currency=”USD” price=25000 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00.000000+00:00′′ add_details=”Axes 4, Payload 6 KG, Reach 0.65m” Let’s look into the Robot, Robot Category, and Manufacturer list. http :8000/robots/ Robot List http :8000/robot-categories/ Robot Category List http :8000/manufacturers/ Manufacturer List In robot categories and manufacturer entry, you can notice that the robots are mentioned in its URL form. Now let’s compose PUT, PATCH, and DELETE requests. We will add a new robot category (Test Category) and manufacturer (Test Manufacturer). The HTTPie command as follows: http POST :8000/robot-categories/ name=”Test Category” notes=”Test” http POST :8000/manufacturers/ name=”Test Manufacturer” rating=1 notes=”Test” Let’s add a few robots that belong to the Test Category and Test Manufacturer. The HTTPie command as follows: http POST :8000/robots/ name=”TEST 1′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test” http POST :8000/robots/ name=”TEST 2′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test” http POST :8000/robots/ name=”TEST 3′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test” Let’s check the entries in the database using the below psql command. select * from robots_robot; Output: You can notice that new entries are added to our database. PUT HTTP verb Now let’s edit the last entry named TEST 3, which has 11 as the primary key, using the PUT HTTP verb. The HTTPUtility Pie command is: http PUT :8000/robots/11 name=”TEST 3′′ robot_category=”Test Category” currency=”USD” price=12000 manufacturer=”Test Manufacturer” manufacturing_date=”2020-10-12 00:00:00.000000+00:00′′ add_details=”Test3′′ Output: The equivalent curl command is curl -iX PUT -H “Content-Type: application/json” -d “{\”name\”:\”TEST 3\”, \”robot_category\”:\”Test Category\”, \”currency\”:\”USD\”, \”price\”:12000, \”manufacturer\”:\”Test Manufacturer\”, \”manufacturing_date\”:\”2020-10-12 00:00:00.000000+00:00\”, \”add_details\”:\”Test3\”}” localhost:8000/robots/11 PATCH HTTP Verb Let’s partially edit the resource that has primary key 11. The HTTPie command for PATCH request is: http PATCH :8000/robots/11 price=15000 add_details=”Test3 Patch” Output: The equivalent curl command is: curl -iX PATCH -H “Content-Type: application/json” -d “{ \”price\”:15000, \”add_details\”:\”Test3 Patch\”}” localhost:8000/robots/11 DELETE HTTP Verb Now, let’s delete the entry that has primary key 11 using DELETE HTTP Verb. The HTTPie command is: http DELETE :8000/robots/11 Output: The equivalent curl command is curl -iX DELETE localhost:8000/robots/11 Now, we need to check what happens if a robot category is deleted. According to our code, if a category is deleted, then all the robots that belong to the particular category should also be cleared. Let’s delete our Test Category (the primary id 3). The HTTPie command is http DELETE :8000/robot-categories/3 Output: Let’s look at the robot table. In total, we added 3 robots (Test 1, Test 2, and Test 3) that belong to Test Category. The robot that has primary id 11 (Test 3) is already deleted using delete request. The remaining two robots with primary id 9 (Test 1) and 10 (Test 2) exist in the database. Since we deleted the Test Category, automatically the other two robots will be cleared from the table. Let’s check the database using the psql command. select * from robots_robot; Output: You can notice that the robots belong to Test Category are cleared successfully. This is made possible with the help of the code, on_delete=models.CASCADE, mentioned while defining the robot category as a foreign key in the robot model. In this article, we learned about generic class views to implement HTTP requests. For this, we used two generic class views from the rest_framework.generics module, ListCreateAPIView and RetrieveUpdateDestroyAPIView. And also we composed different HTTP requests to interact with related resources. Django-REST Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 288, "s": 28, "text": "In this article, we will create class-based views and combine this with the serializer class to return JSON representation for each HTTP request. For our class-based views, we will make use of a set of generic views, which help to achieve minimum lines code. " }, { "code": null, "e": 317, "s": 288, "text": "Generic Classes and Viewsets" }, { "code": null, "e": 371, "s": 317, "text": "HTTP requests to interact with relationship resources" }, { "code": null, "e": 581, "s": 371, "text": "We will take advantage of generic class views to implement get, post, delete, put, and patch methods. For this, we need to make use of two generic class views from the rest_framework.generics module. They are:" }, { "code": null, "e": 599, "s": 581, "text": "ListCreateAPIView" }, { "code": null, "e": 628, "s": 599, "text": "RetrieveUpdateDestroyAPIView" }, { "code": null, "e": 983, "s": 628, "text": "The ListCreateAPIView class view implements the get method (retrieves a listing of a queryset) and post method (creates a model instance). And, the RetrieveUpdateDestroyAPIView class view implements get (retrieve a model instance), delete (delete a model instance), put (completely update a model instance), and patch (partially update a model instance)." }, { "code": null, "e": 1255, "s": 983, "text": "In the Django REST framework, these two generic views are implemented as mixin classes. The ListCreateAPIView uses ListModelMixin and CreateModelMixin from rest_framework.mixins module and GenericAPIView from rest_framework.generics module. Let’s look at its declaration." }, { "code": null, "e": 1263, "s": 1255, "text": "Python3" }, { "code": "class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView):", "e": 1376, "s": 1263, "text": null }, { "code": null, "e": 1594, "s": 1376, "text": "The RetrieveUpdateDestroyAPIView uses RetrieveModelMixin, UpdateModelMixin and DestroyModelMixin from rest_framework.mixins module and GenericAPIView from rest_framework.generics module. Let’s look at its declaration." }, { "code": null, "e": 1602, "s": 1594, "text": "Python3" }, { "code": "class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView):", "e": 1837, "s": 1602, "text": null }, { "code": null, "e": 2034, "s": 1837, "text": "Now, let’s get back to our RESTFul web service code and create the required set of Django class-based views. You can open the restpi\\robots\\views.py Python file and replace it with the below code." }, { "code": null, "e": 2042, "s": 2034, "text": "Python3" }, { "code": "from django.shortcuts import render from rest_framework import genericsfrom rest_framework.response import Responsefrom rest_framework.reverse import reverse from robots.models import RobotCategoryfrom robots.models import Manufacturerfrom robots.models import Robot from robots.serializers import RobotCategorySerializerfrom robots.serializers import ManufacturerSerializerfrom robots.serializers import RobotSerializer class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) }) class RobotCategoryList(generics.ListCreateAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer class RobotCategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = RobotCategory.objects.all() serializer_class = RobotCategorySerializer name = 'robotcategory-detail' class ManufacturerList(generics.ListCreateAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-list' class ManufacturerDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Manufacturer.objects.all() serializer_class = ManufacturerSerializer name = 'manufacturer-detail' class RobotList(generics.ListCreateAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-list' class RobotDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Robot.objects.all() serializer_class = RobotSerializer name = 'robot-detail'", "e": 3839, "s": 2042, "text": null }, { "code": null, "e": 4333, "s": 3839, "text": "Here the RobotCategoryList, ManufacturerList, and RobotList are the subclasses of generics.ListCreateAPIView; the RobotCategoryDetail, ManufacturerDetail, and RobotDetail are the subclasses of generics.RetrieveUpdateDestroyAPIView. Every subclass has a queryset attribute, serializer_class attribute, and a name attribute. The queryset attribute stores all the retrieved objects, the serializer_class attribute stores the serializer class, and the name attribute is used to identify each view." }, { "code": null, "e": 4464, "s": 4333, "text": "Apart from class-based views, you can notice an ApiRoot class, which is a subclass of the rest_framework.generics.GenericAPIView. " }, { "code": null, "e": 4472, "s": 4464, "text": "Python3" }, { "code": "class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'robot-categories': reverse(RobotCategoryList.name, request=request), 'manufacturers': reverse(ManufacturerList.name, request=request), 'robots': reverse(RobotList.name, request=request) })", "e": 4836, "s": 4472, "text": null }, { "code": null, "e": 5179, "s": 4836, "text": "The ApiRoot class creates an end-point for the root of our RESTful web service that facilitates browsing the resource collection. The get method defines in this class returns a Response object that has the descriptive name and its URL. Here, it returns descriptive name and URL for robot categories list, manufacturers list, and robots list. " }, { "code": null, "e": 5516, "s": 5179, "text": "Next, we need to specify the URL pattern in the regular expression to run a specific method for a class-based view defined in the views.py Python file. The client HTTP request has to match with this regular expression to run the methods in the views.py file. You can create the urls.py file in the restapi/robots and add the below code." }, { "code": null, "e": 5524, "s": 5516, "text": "Python3" }, { "code": "from django.conf.urls import urlfrom robots import views urlpatterns = [ url(r'^robot-categories/$', views.RobotCategoryList.as_view(), name=views.RobotCategoryList.name), url(r'^robot-categories/(?P<pk>[0-9]+)$', views.RobotCategoryDetail.as_view(), name=views.RobotCategoryDetail.name), url(r'^manufacturers/$', views.ManufacturerList.as_view(), name=views.ManufacturerList.name), url(r'^manufacturers/(?P<pk>[0-9]+)$', views.ManufacturerDetail.as_view(), name=views.ManufacturerDetail.name), url(r'^robots/$', views.RobotList.as_view(), name=views.RobotList.name), url(r'^robots/(?P<pk>[0-9]+)$', views.RobotDetail.as_view(), name=views.RobotDetail.name), url(r'^$', views.ApiRoot.as_view(), name=views.ApiRoot.name),]", "e": 6392, "s": 5524, "text": null }, { "code": null, "e": 6544, "s": 6392, "text": "As a final step, we need to define the root URL configuration. You can open the restapi/restapi/urls.py Python file and replace it with the below code:" }, { "code": null, "e": 6552, "s": 6544, "text": "Python3" }, { "code": "from django.conf.urls import url, include urlpatterns = [ url(r'^', include('robots.urls')),]", "e": 6650, "s": 6552, "text": null }, { "code": null, "e": 6808, "s": 6650, "text": "It is time to test our code by composing and sending the various HTTP requests. Here, we will take advantage of both the HTTPie command and the CURL command." }, { "code": null, "e": 6907, "s": 6808, "text": "Let’s compose and send an HTTP Post request to create a new robot category. The HTTPie command is:" }, { "code": null, "e": 7088, "s": 6907, "text": "http POST :8000/robot-categories/ name=”Articulated Robots” notes=”Flexibility, dexterity, and reach make articulated robots ideally suited for tasks that span non-parallel planes”" }, { "code": null, "e": 7096, "s": 7088, "text": "Output:" }, { "code": null, "e": 7133, "s": 7096, "text": "Robot Category Post Request (HTTPie)" }, { "code": null, "e": 7194, "s": 7133, "text": "Let’s create another robot category using the curl command. " }, { "code": null, "e": 7468, "s": 7194, "text": "curl -iX POST -H “Content-Type: application/json” -d “{\\”name\\”:\\”SCARA Robots\\”, \\”notes\\”:\\”A Selective Compliance Articulated Robot Arm (SCARA) is a good and cost-effective choice for performing operations between two parallel planes\\”}” localhost:8000/robot-categories/" }, { "code": null, "e": 7476, "s": 7468, "text": "Output:" }, { "code": null, "e": 7511, "s": 7476, "text": "Robot Category POST request (cURL)" }, { "code": null, "e": 7596, "s": 7511, "text": "Let’s compose a GET request to retrieve all robot categories. The HTTPie command is:" }, { "code": null, "e": 7625, "s": 7596, "text": "http :8000/robot-categories/" }, { "code": null, "e": 7633, "s": 7625, "text": "Output:" }, { "code": null, "e": 7685, "s": 7633, "text": "Robot Category GET request (HTTPie utility command)" }, { "code": null, "e": 7716, "s": 7685, "text": "The equivalent curl command is" }, { "code": null, "e": 7762, "s": 7716, "text": "curl -iX GET localhost:8000/robot-categories/" }, { "code": null, "e": 7770, "s": 7762, "text": "Output:" }, { "code": null, "e": 7789, "s": 7770, "text": "GET request (cURL)" }, { "code": null, "e": 7841, "s": 7789, "text": "The HTTPie command to retrieve a robot category is:" }, { "code": null, "e": 7871, "s": 7841, "text": "http :8000/robot-categories/1" }, { "code": null, "e": 7879, "s": 7871, "text": "Output:" }, { "code": null, "e": 7909, "s": 7879, "text": "GET request (single category)" }, { "code": null, "e": 7941, "s": 7909, "text": "The equivalent curl command is:" }, { "code": null, "e": 7988, "s": 7941, "text": "curl -iX GET localhost:8000/robot-categories/1" }, { "code": null, "e": 8081, "s": 7988, "text": "Let’s compose and send an HTTP POST request to create a manufacturer. The HTTPie command is:" }, { "code": null, "e": 8204, "s": 8081, "text": "http :8000/manufacturers/ name=”FANUC Global” rating=4 notes=”The automation specialist and industrial robot manufacturer”" }, { "code": null, "e": 8212, "s": 8204, "text": "Output:" }, { "code": null, "e": 8233, "s": 8212, "text": "HTTP/1.1 201 Created" }, { "code": null, "e": 8265, "s": 8233, "text": "Allow: GET, POST, HEAD, OPTIONS" }, { "code": null, "e": 8285, "s": 8265, "text": "Content-Length: 219" }, { "code": null, "e": 8316, "s": 8285, "text": "Content-Type: application/json" }, { "code": null, "e": 8352, "s": 8316, "text": "Date: Mon, 16 Nov 2020 06:36:12 GMT" }, { "code": null, "e": 8400, "s": 8352, "text": "Location: http://localhost:8000/manufacturers/1" }, { "code": null, "e": 8429, "s": 8400, "text": "Referrer-Policy: same-origin" }, { "code": null, "e": 8466, "s": 8429, "text": "Server: WSGIServer/0.2 CPython/3.7.5" }, { "code": null, "e": 8487, "s": 8466, "text": "Vary: Accept, Cookie" }, { "code": null, "e": 8519, "s": 8487, "text": "X-Content-Type-Options: nosniff" }, { "code": null, "e": 8541, "s": 8519, "text": "X-Frame-Options: DENY" }, { "code": null, "e": 8543, "s": 8541, "text": "{" }, { "code": null, "e": 8592, "s": 8543, "text": " “entry_date”: “2020-11-16T06:36:12.449074Z”," }, { "code": null, "e": 8610, "s": 8592, "text": " “robots”: []," }, { "code": null, "e": 8638, "s": 8610, "text": " “name”: “FANUC Global”," }, { "code": null, "e": 8714, "s": 8638, "text": " “notes”: “The automation specialist and industrial robot manufacturer”," }, { "code": null, "e": 8727, "s": 8714, "text": " “pk”: 1," }, { "code": null, "e": 8744, "s": 8727, "text": " “rating”: 4," }, { "code": null, "e": 8795, "s": 8744, "text": " “url”: “http://localhost:8000/manufacturers/1”" }, { "code": null, "e": 8797, "s": 8795, "text": "}" }, { "code": null, "e": 8855, "s": 8797, "text": "Let’s create another manufacturer using the curl command." }, { "code": null, "e": 9080, "s": 8855, "text": "curl -iX POST -H “Content-Type: application/json” -d “{\\”name\\”:\\”ABB\\”, \\”rating\\”:5, \\”notes\\”:\\”Focused in Electrification, Industrial Automation, Robotics, Discrete Automation and Motion\\”}” localhost:8000/manufacturers/" }, { "code": null, "e": 9088, "s": 9080, "text": "Output:" }, { "code": null, "e": 9109, "s": 9088, "text": "HTTP/1.1 201 Created" }, { "code": null, "e": 9145, "s": 9109, "text": "Date: Mon, 16 Nov 2020 06:49:43 GMT" }, { "code": null, "e": 9182, "s": 9145, "text": "Server: WSGIServer/0.2 CPython/3.7.5" }, { "code": null, "e": 9213, "s": 9182, "text": "Content-Type: application/json" }, { "code": null, "e": 9261, "s": 9213, "text": "Location: http://localhost:8000/manufacturers/2" }, { "code": null, "e": 9282, "s": 9261, "text": "Vary: Accept, Cookie" }, { "code": null, "e": 9314, "s": 9282, "text": "Allow: GET, POST, HEAD, OPTIONS" }, { "code": null, "e": 9336, "s": 9314, "text": "X-Frame-Options: DENY" }, { "code": null, "e": 9356, "s": 9336, "text": "Content-Length: 242" }, { "code": null, "e": 9388, "s": 9356, "text": "X-Content-Type-Options: nosniff" }, { "code": null, "e": 9417, "s": 9388, "text": "Referrer-Policy: same-origin" }, { "code": null, "e": 9497, "s": 9417, "text": "{“url”:”http://localhost:8000/manufacturers/2′′,”pk”:2,”name”:”ABB”,”rating”:5," }, { "code": null, "e": 9588, "s": 9497, "text": "“notes”:”Focused in Electrification, Industrial Automation, Robotics, Discrete Automation " }, { "code": null, "e": 9656, "s": 9588, "text": "and Motion”,”entry_date”:”2020-11-16T06:49:43.108992Z”,”robots”:[]}" }, { "code": null, "e": 9731, "s": 9656, "text": "Let’s compose a request to retrieve a manufacturer. The HTTPie command is:" }, { "code": null, "e": 9758, "s": 9731, "text": "http :8000/manufacturers/2" }, { "code": null, "e": 9766, "s": 9758, "text": "Output:" }, { "code": null, "e": 9797, "s": 9766, "text": "Retrieve a single manufacturer" }, { "code": null, "e": 9830, "s": 9797, "text": "The equivalent curl command is: " }, { "code": null, "e": 9874, "s": 9830, "text": "curl -iX GET localhost:8000/manufacturers/2" }, { "code": null, "e": 10025, "s": 9874, "text": "We have populated the robot category and manufacturer details. Now, let’s compose and send a POST request to add robot details. The HTTPie command is " }, { "code": null, "e": 10271, "s": 10025, "text": "http POST :8000/robots/ name=”FANUC M-710ic/50′′ robot_category=”Articulated Robots” currency=”USD” price=37000 manufacturer=”FANUC Global” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Axes 6, Payload 50 KG, Reach 2050 MM”" }, { "code": null, "e": 10279, "s": 10271, "text": "Output:" }, { "code": null, "e": 10318, "s": 10279, "text": "Robot Entry (HTTP Utility Pie command)" }, { "code": null, "e": 10370, "s": 10318, "text": "Let’s compose a curl command to create a new entry." }, { "code": null, "e": 10698, "s": 10370, "text": "curl -iX POST -H “Content-Type: application/json” -d “{\\”name\\”:\\”SR-3iA\\”, \\”robot_category\\”:\\”SCARA Robots\\”, \\”currency\\”:\\”USD\\”, \\”price\\”:37000, \\”manufacturer\\”:\\”FANUC Global\\”, \\”manufacturing_date\\”:\\”2019-10-12 00:00:00.000000+00:00\\”, \\”add_details\\”:\\”Axis 4, Payload 3 KG, Reach 400 MM\\”}” localhost:8000/robots/" }, { "code": null, "e": 10706, "s": 10698, "text": "Output:" }, { "code": null, "e": 10770, "s": 10706, "text": "Let’s add a few more entries in Robot. The HTTPie commands are:" }, { "code": null, "e": 10995, "s": 10770, "text": "http POST :8000/robots/ name=”IRB 120′′ robot_category=”Articulated Robots” currency=”USD” price=14500 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00.000000+00:00′′ add_details=”Axes 6, Payload 3 KG, Reach 0.58m”" }, { "code": null, "e": 11215, "s": 10995, "text": "http POST :8000/robots/ name=”IRB 910SC” robot_category=”SCARA Robots” currency=”USD” price=25000 manufacturer=”ABB” manufacturing_date=”2020-05-10 00:00:00.000000+00:00′′ add_details=”Axes 4, Payload 6 KG, Reach 0.65m”" }, { "code": null, "e": 11282, "s": 11215, "text": "Let’s look into the Robot, Robot Category, and Manufacturer list. " }, { "code": null, "e": 11301, "s": 11282, "text": "http :8000/robots/" }, { "code": null, "e": 11312, "s": 11301, "text": "Robot List" }, { "code": null, "e": 11341, "s": 11312, "text": "http :8000/robot-categories/" }, { "code": null, "e": 11361, "s": 11341, "text": "Robot Category List" }, { "code": null, "e": 11387, "s": 11361, "text": "http :8000/manufacturers/" }, { "code": null, "e": 11405, "s": 11387, "text": "Manufacturer List" }, { "code": null, "e": 11512, "s": 11405, "text": "In robot categories and manufacturer entry, you can notice that the robots are mentioned in its URL form. " }, { "code": null, "e": 11681, "s": 11512, "text": "Now let’s compose PUT, PATCH, and DELETE requests. We will add a new robot category (Test Category) and manufacturer (Test Manufacturer). The HTTPie command as follows:" }, { "code": null, "e": 11749, "s": 11681, "text": "http POST :8000/robot-categories/ name=”Test Category” notes=”Test”" }, { "code": null, "e": 11827, "s": 11749, "text": "http POST :8000/manufacturers/ name=”Test Manufacturer” rating=1 notes=”Test”" }, { "code": null, "e": 11937, "s": 11827, "text": "Let’s add a few robots that belong to the Test Category and Test Manufacturer. The HTTPie command as follows:" }, { "code": null, "e": 12141, "s": 11937, "text": "http POST :8000/robots/ name=”TEST 1′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test”" }, { "code": null, "e": 12345, "s": 12141, "text": "http POST :8000/robots/ name=”TEST 2′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test”" }, { "code": null, "e": 12549, "s": 12345, "text": "http POST :8000/robots/ name=”TEST 3′′ robot_category=”Test Category” currency=”USD” price=37000 manufacturer=”Test Manufacturer” manufacturing_date=”2019-10-12 00:00:00.000000+00:00′′ add_details=”Test”" }, { "code": null, "e": 12620, "s": 12549, "text": "Let’s check the entries in the database using the below psql command. " }, { "code": null, "e": 12648, "s": 12620, "text": "select * from robots_robot;" }, { "code": null, "e": 12656, "s": 12648, "text": "Output:" }, { "code": null, "e": 12716, "s": 12656, "text": "You can notice that new entries are added to our database. " }, { "code": null, "e": 12730, "s": 12716, "text": "PUT HTTP verb" }, { "code": null, "e": 12832, "s": 12730, "text": "Now let’s edit the last entry named TEST 3, which has 11 as the primary key, using the PUT HTTP verb." }, { "code": null, "e": 12864, "s": 12832, "text": "The HTTPUtility Pie command is:" }, { "code": null, "e": 13072, "s": 12864, "text": "http PUT :8000/robots/11 name=”TEST 3′′ robot_category=”Test Category” currency=”USD” price=12000 manufacturer=”Test Manufacturer” manufacturing_date=”2020-10-12 00:00:00.000000+00:00′′ add_details=”Test3′′" }, { "code": null, "e": 13080, "s": 13072, "text": "Output:" }, { "code": null, "e": 13111, "s": 13080, "text": "The equivalent curl command is" }, { "code": null, "e": 13417, "s": 13111, "text": "curl -iX PUT -H “Content-Type: application/json” -d “{\\”name\\”:\\”TEST 3\\”, \\”robot_category\\”:\\”Test Category\\”, \\”currency\\”:\\”USD\\”, \\”price\\”:12000, \\”manufacturer\\”:\\”Test Manufacturer\\”, \\”manufacturing_date\\”:\\”2020-10-12 00:00:00.000000+00:00\\”, \\”add_details\\”:\\”Test3\\”}” localhost:8000/robots/11" }, { "code": null, "e": 13433, "s": 13417, "text": "PATCH HTTP Verb" }, { "code": null, "e": 13533, "s": 13433, "text": "Let’s partially edit the resource that has primary key 11. The HTTPie command for PATCH request is:" }, { "code": null, "e": 13599, "s": 13533, "text": "http PATCH :8000/robots/11 price=15000 add_details=”Test3 Patch”" }, { "code": null, "e": 13607, "s": 13599, "text": "Output:" }, { "code": null, "e": 13639, "s": 13607, "text": "The equivalent curl command is:" }, { "code": null, "e": 13772, "s": 13639, "text": "curl -iX PATCH -H “Content-Type: application/json” -d “{ \\”price\\”:15000, \\”add_details\\”:\\”Test3 Patch\\”}” localhost:8000/robots/11" }, { "code": null, "e": 13789, "s": 13772, "text": "DELETE HTTP Verb" }, { "code": null, "e": 13888, "s": 13789, "text": "Now, let’s delete the entry that has primary key 11 using DELETE HTTP Verb. The HTTPie command is:" }, { "code": null, "e": 13916, "s": 13888, "text": "http DELETE :8000/robots/11" }, { "code": null, "e": 13924, "s": 13916, "text": "Output:" }, { "code": null, "e": 13956, "s": 13924, "text": "The equivalent curl command is " }, { "code": null, "e": 13997, "s": 13956, "text": "curl -iX DELETE localhost:8000/robots/11" }, { "code": null, "e": 14269, "s": 13997, "text": "Now, we need to check what happens if a robot category is deleted. According to our code, if a category is deleted, then all the robots that belong to the particular category should also be cleared. Let’s delete our Test Category (the primary id 3). The HTTPie command is" }, { "code": null, "e": 14306, "s": 14269, "text": "http DELETE :8000/robot-categories/3" }, { "code": null, "e": 14314, "s": 14306, "text": "Output:" }, { "code": null, "e": 14758, "s": 14314, "text": "Let’s look at the robot table. In total, we added 3 robots (Test 1, Test 2, and Test 3) that belong to Test Category. The robot that has primary id 11 (Test 3) is already deleted using delete request. The remaining two robots with primary id 9 (Test 1) and 10 (Test 2) exist in the database. Since we deleted the Test Category, automatically the other two robots will be cleared from the table. Let’s check the database using the psql command." }, { "code": null, "e": 14786, "s": 14758, "text": "select * from robots_robot;" }, { "code": null, "e": 14794, "s": 14786, "text": "Output:" }, { "code": null, "e": 15031, "s": 14794, "text": "You can notice that the robots belong to Test Category are cleared successfully. This is made possible with the help of the code, on_delete=models.CASCADE, mentioned while defining the robot category as a foreign key in the robot model." }, { "code": null, "e": 15329, "s": 15031, "text": "In this article, we learned about generic class views to implement HTTP requests. For this, we used two generic class views from the rest_framework.generics module, ListCreateAPIView and RetrieveUpdateDestroyAPIView. And also we composed different HTTP requests to interact with related resources." }, { "code": null, "e": 15341, "s": 15329, "text": "Django-REST" }, { "code": null, "e": 15355, "s": 15341, "text": "Python Django" }, { "code": null, "e": 15362, "s": 15355, "text": "Python" }, { "code": null, "e": 15460, "s": 15362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15492, "s": 15460, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 15519, "s": 15492, "text": "Python Classes and Objects" }, { "code": null, "e": 15540, "s": 15519, "text": "Python OOPs Concepts" }, { "code": null, "e": 15563, "s": 15540, "text": "Introduction To PYTHON" }, { "code": null, "e": 15619, "s": 15563, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 15650, "s": 15619, "text": "Python | os.path.join() method" }, { "code": null, "e": 15692, "s": 15650, "text": "Check if element exists in list in Python" }, { "code": null, "e": 15734, "s": 15692, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 15773, "s": 15734, "text": "Python | Get unique values from a list" } ]
Splitting stereo audio to mono with PyDub
16 Mar, 2021 Splitting a stereo audio file into multiple mono audio files is very useful if you are trying to process or transcribe the stereo audio files. This is because stereo audio has 2 audio sources on different channels which makes it very hard to process the file. Splitting the stereo audio file into mono audio files makes this job easier. For this article, we will be using the Pydub python module, which is very useful for working with audio files and modifying them. For more information read this Pydub article. Pydub installation using pip: pip install pydub Stereo Audio: It is a 2 channel audio, which means that two or more sound sources are localized to the left and right side while listening. This is most commonly used in Audio or Video streaming services where sounds of different instruments can be heard from specific sides of the headphones. Mono Audio: It is single-channel audio, which means that all sound sources are heard through one channel only. This means that you will hear the same sound on the left and right sides of the headphones. This is the format in which the phone microphone records audio. Folder Structure In a folder named pydub, I have my python code file named main.py having the below code, and a test audio file named stereo_audio.wav. Initial Folder Structure Explanation Import AudioSegment from pydubOpen an audio file as an AudioSegment instance using AudioSegment.from_file() method.Call the split_to_mono method on the file which splits the stereo audio file into left and right channel audio and returns a list where the left channel AudioSegment object is at 0 index and the right channel one is at 1 index.Export/Save both the mono audio files in the desired format. Import AudioSegment from pydub Open an audio file as an AudioSegment instance using AudioSegment.from_file() method. Call the split_to_mono method on the file which splits the stereo audio file into left and right channel audio and returns a list where the left channel AudioSegment object is at 0 index and the right channel one is at 1 index. Export/Save both the mono audio files in the desired format. Note: Remember to change the file paths according to your system. Implementation: Python3 # Python3 program to illustrate# splitting stereo audio to mono# using pydub # Import AudioSegment from pydubfrom pydub import AudioSegment # Open the stereo audio file as# an AudioSegment instancestereo_audio = AudioSegment.from_file( "C:\\Users\\NEERAJ RANA\\Desktop\\GFG_Articles\\pydub\\stereo_audio.wav", format="wav") # Calling the split_to_mono method# on the stereo audio filemono_audios = stereo_audio.split_to_mono() # Exporting/Saving the two mono# audio files present at index 0(left)# and index 1(right) of list returned# by split_to_mono methodmono_left = mono_audios[0].export( "C:\\Users\\NEERAJ RANA\\Desktop\\GFG_Articles\\pydub\\mono_left.wav", format="wav")mono_right = mono_audios[1].export( "C:\\Users\\NEERAJ RANA\\Desktop\\GFG_Articles\\pydub\\mono_right.wav", format="wav") Output: Folder Structure After Running Code Output Video: Picked python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Mar, 2021" }, { "code": null, "e": 365, "s": 28, "text": "Splitting a stereo audio file into multiple mono audio files is very useful if you are trying to process or transcribe the stereo audio files. This is because stereo audio has 2 audio sources on different channels which makes it very hard to process the file. Splitting the stereo audio file into mono audio files makes this job easier." }, { "code": null, "e": 541, "s": 365, "text": "For this article, we will be using the Pydub python module, which is very useful for working with audio files and modifying them. For more information read this Pydub article." }, { "code": null, "e": 571, "s": 541, "text": "Pydub installation using pip:" }, { "code": null, "e": 589, "s": 571, "text": "pip install pydub" }, { "code": null, "e": 883, "s": 589, "text": "Stereo Audio: It is a 2 channel audio, which means that two or more sound sources are localized to the left and right side while listening. This is most commonly used in Audio or Video streaming services where sounds of different instruments can be heard from specific sides of the headphones." }, { "code": null, "e": 1150, "s": 883, "text": "Mono Audio: It is single-channel audio, which means that all sound sources are heard through one channel only. This means that you will hear the same sound on the left and right sides of the headphones. This is the format in which the phone microphone records audio." }, { "code": null, "e": 1167, "s": 1150, "text": "Folder Structure" }, { "code": null, "e": 1302, "s": 1167, "text": "In a folder named pydub, I have my python code file named main.py having the below code, and a test audio file named stereo_audio.wav." }, { "code": null, "e": 1327, "s": 1302, "text": "Initial Folder Structure" }, { "code": null, "e": 1339, "s": 1327, "text": "Explanation" }, { "code": null, "e": 1742, "s": 1339, "text": "Import AudioSegment from pydubOpen an audio file as an AudioSegment instance using AudioSegment.from_file() method.Call the split_to_mono method on the file which splits the stereo audio file into left and right channel audio and returns a list where the left channel AudioSegment object is at 0 index and the right channel one is at 1 index.Export/Save both the mono audio files in the desired format." }, { "code": null, "e": 1773, "s": 1742, "text": "Import AudioSegment from pydub" }, { "code": null, "e": 1859, "s": 1773, "text": "Open an audio file as an AudioSegment instance using AudioSegment.from_file() method." }, { "code": null, "e": 2087, "s": 1859, "text": "Call the split_to_mono method on the file which splits the stereo audio file into left and right channel audio and returns a list where the left channel AudioSegment object is at 0 index and the right channel one is at 1 index." }, { "code": null, "e": 2148, "s": 2087, "text": "Export/Save both the mono audio files in the desired format." }, { "code": null, "e": 2214, "s": 2148, "text": "Note: Remember to change the file paths according to your system." }, { "code": null, "e": 2230, "s": 2214, "text": "Implementation:" }, { "code": null, "e": 2238, "s": 2230, "text": "Python3" }, { "code": "# Python3 program to illustrate# splitting stereo audio to mono# using pydub # Import AudioSegment from pydubfrom pydub import AudioSegment # Open the stereo audio file as# an AudioSegment instancestereo_audio = AudioSegment.from_file( \"C:\\\\Users\\\\NEERAJ RANA\\\\Desktop\\\\GFG_Articles\\\\pydub\\\\stereo_audio.wav\", format=\"wav\") # Calling the split_to_mono method# on the stereo audio filemono_audios = stereo_audio.split_to_mono() # Exporting/Saving the two mono# audio files present at index 0(left)# and index 1(right) of list returned# by split_to_mono methodmono_left = mono_audios[0].export( \"C:\\\\Users\\\\NEERAJ RANA\\\\Desktop\\\\GFG_Articles\\\\pydub\\\\mono_left.wav\", format=\"wav\")mono_right = mono_audios[1].export( \"C:\\\\Users\\\\NEERAJ RANA\\\\Desktop\\\\GFG_Articles\\\\pydub\\\\mono_right.wav\", format=\"wav\")", "e": 3059, "s": 2238, "text": null }, { "code": null, "e": 3067, "s": 3059, "text": "Output:" }, { "code": null, "e": 3103, "s": 3067, "text": "Folder Structure After Running Code" }, { "code": null, "e": 3117, "s": 3103, "text": "Output Video:" }, { "code": null, "e": 3124, "s": 3117, "text": "Picked" }, { "code": null, "e": 3139, "s": 3124, "text": "python-modules" }, { "code": null, "e": 3146, "s": 3139, "text": "Python" } ]
Web Scraping using Python and Scrapy?
One of the best frameworks for developing crawlers is scrapy. Scrapy is a popular web scraping and crawling framework utilizing high-level functionality to make scraping websites easier. Installing scrapy in windows is easy: we can use either pip or conda(if you have anaconda). Scrapy runs on both python 2 and 3 versions. pip install Scrapy Or conda install –c conda-forge scrapy If Scrapy is installed correctly, a scrapy command will now be available in the terminal − C:\Users\rajesh>scrapy Scrapy 1.6.0 - no active project Usage: scrapy <command> [options] [args] Available commands: bench Run quick benchmark test fetch Fetch a URL using the Scrapy downloader genspider Generate new spider using pre-defined templates runspider Run a self-contained spider (without creating a project) settings Get settings values shell Interactive scraping console startproject Create new project version Print Scrapy version view Open URL in browser, as seen by Scrapy [ more ] More commands available when run from project directory Use "scrapy <command> -h" to see more info about a command. Now that Scrapy is installed, we can run the startproject command to generate the default structure for our first Scrapy project. To do this, open the terminal and navigate to the directory where you want to store your Scrapy project, and then run scrapy startproject <project name>. Below I'm using the scrapy_example for the project name − C:\Users\rajesh>scrapy startproject scrapy_example New Scrapy project 'scrapy_example', using template directory 'c:\python\python361\lib\site-packages\scrapy\templates\project', created in: C:\Users\rajesh\scrapy_example You can start your first spider with: cd scrapy_example scrapy genspider example example.com C:\Users\rajesh>cd scrapy_example C:\Users\rajesh\scrapy_example>tree /F Folder PATH listing Volume serial number is 8CD6-8D39 C:. │ scrapy.cfg │ └───scrapy_example │ items.py │ middlewares.py │ pipelines.py │ settings.py │ __init__.py │ ├───spiders │ │ __init__.py │ │ │ └───__pycache__ └───__pycache__ Another way is we run the scrapy shell and do web scrapping, like below − In [18]: fetch ("https://www.wsj.com/india") 019-02-04 22:38:53 [scrapy.core.engine] DEBUG: Crawled (200) https://www.wsj.com/india> (referer: None) The scrapy crawler will return a "response" object that contains the downloaded information. Let's check what our above crawler contain − In [19]: view(response) Out[19]: True And in your default browser, the web link will open & you will see something like − Great, that looks somewhat similar to our web page, so the crawler has successfully download the entire web page. Now let's what our crawler contains − In [22]: print(response.text) <!DOCTYPE html> <html data-region = "asia,india" data-protocol = "https" data-reactid = ".2316x0ul96e" data-react-checksum = "851122071"> <head data-reactid = ".2316x0ul96e.0"> <title data-reactid = ".2316x0ul96e.0.0">The Wall Street Journal & Breaking News, Business, Financial and Economic News, World News and Video</title> <meta http-equiv = "X-UA-Compatible" content = "IE = edge" data-reactid = ".2316x0ul96e.0.1"/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" data-reactid = ".2316x0ul96e.0.2"/> <meta name = "viewport" content = "initial-scale = 1.0001, minimum-scale = 1.0001, maximum-scale = 1.0001, user-scalable = no" data-reactid = ".2316x0ul96e.0.3"/> <meta name = "description" content = "WSJ online coverage of breaking news and current headlines from the US and around the world. Top stories, photos, videos, detailed analysis and in-depth reporting." data-reactid = ".2316x0ul96e.0.4"/> <meta name = "keywords" content = "News, breaking news, latest news, US news, headlines, world news, business, finances, politics, WSJ, WSJ news, WSJ.com, Wall Street Journal" data-reactid = ".2316x0ul96e.0.5"/> <meta name = "page.site" content = "wsj" data-reactid = ".2316x0ul96e.0.7"/> <meta name = "page.site.product" content = "WSJ" data-reactid = ".2316x0ul96e.0.8"/> <meta name = "stack.name" content = "dj01:vir:prod-sections" data-reactid = ".2316x0ul96e.0.9"/> <meta name = "referrer" content = "always" data-reactid = ".2316x0ul96e.0.a"/> <link rel = "canonical" href = "https://www.wsj.com/india/" data-reactid = ".2316x0ul96e.0.b"/> <meta nameproperty = "og:url" content = "https://www.wsj.com/india/" data-reactid = ".2316x0ul96e.0.c:$0"/> <meta nameproperty = "og:title" content = "The Wall Street Journal & Breaking News, Business, Financial and Economic News, World News and Video" data-reactid = ".2316x0ul96e.0.c:$1"/> <meta nameproperty = "og:description" content = "WSJ online coverage of breaking news and current headlines from the US and around the world. Top stories, photos, videos, detailed analysis and in-depth reporting." data-reactid = ".2316x0ul96e.0.c:$2"/> <meta nameproperty = "og:type" content = "website" data-reactid = ".2316x0ul96e.0.c:$3"/> <meta nameproperty = "og:site_name" content = "The Wall Street Journal" data-reactid = ".2316x0ul96e.0.c:$4"/> <meta nameproperty = "og:image" content = "https://s.wsj.net/img/meta/wsj-social-share.png" data-reactid = ".2316x0ul96e.0.c:$5"/> <meta name = "twitter:site" content = "@wsj" data-reactid = ".2316x0ul96e.0.c:$6"/> <meta name = "twitter:app:name:iphone" content = "The Wall Street Journal" data-reactid = ".2316x0ul96e.0.c:$7"/> <meta name = "twitter:app:name:googleplay" content = "The Wall Street Journal" data-reactid = " "/> ...& so much more: Scrapy provides ways to extract information from HTML based on css selectors like class, id etc. To find the css selector for title of any webpage title, simply right click and click inspect, like below: This is will open the developer tools in your browser window − As it can be seen, the css class "wsj-headline-link" is applied to all anchor(<a>) tags that have titles. With this information, we'll try to find all the titles from the rest of the contents in the response object − The response.css() is the function that will extract content based on css selector passed to it (like anchor tag above). Let's see some more example of our response.css function. In [24]: response.css(".wsj-headline-link::text").extract_first() Out[24]: 'China Fears Loom Over Stocks After January Surge' and In [25]: response.css(".wsj-headline-link").extract_first() Out[25]: '<a class="wsj-headline-link" href = "https://www.wsj.com/articles/china-fears-loom-over-stocks-after-january-surge-11549276200" data-reactid=".2316x0ul96e.1.1.5.1.0.3.3.0.0.0:$0.1.0">China Fears Loom Over Stocks After January Surge</a>' To get all the links from the webpage − links = response.css('a::attr(href)').extract() ['https://www.google.com/intl/en_us/chrome/browser/desktop/index.html', 'https://support.apple.com/downloads/', 'https://www.mozilla.org/en-US/firefox/new/', 'https://windows.microsoft.com/en-us/internet-explorer/download-ie', 'https://www.barrons.com', 'http://bigcharts.marketwatch.com', 'https://www.wsj.com/public/page/wsj-x-marketing.html', 'https://www.dowjones.com/', 'https://global.factiva.com/factivalogin/login.asp?productname=global', 'https://www.fnlondon.com/', 'https://www.mansionglobal.com/', 'https://www.marketwatch.com', 'https://newsplus.wsj.com', 'https://privatemarkets.dowjones.com', 'https://djlogin.dowjones.com/login.asp?productname=rnc', 'https://www.wsj.com/conferences', 'https://www.wsj.com/pro/centralbanking', 'https://www.wsj.com/video/', 'https://www.wsj.com', 'http://www.bigdecisions.com/', 'https://www.businessspectator.com.au/', 'https://www.checkout51.com/?utm_source=wsj&utm_medium=digitalhousead&utm_campaign=wsjspotlight', 'https://www.harpercollins.com/', 'https://housing.com/', 'https://www.makaan.com/', 'https://nypost.com/', 'https://www.newsamerica.com/', 'https://www.proptiger.com', 'https://www.rea-group.com/', ...... ...... To get the comment count from the wsj(wall street journel) webpage − In [38]: response.css(".wsj-comment-count::text").extract() Out[38]: ['71', '59'] Above is just the introduction to web-scraping through scrapy, we can do lot more with scrapy.
[ { "code": null, "e": 1374, "s": 1187, "text": "One of the best frameworks for developing crawlers is scrapy. Scrapy is a popular web scraping and crawling framework utilizing high-level functionality to make scraping websites easier." }, { "code": null, "e": 1511, "s": 1374, "text": "Installing scrapy in windows is easy: we can use either pip or conda(if you have anaconda). Scrapy runs on both python 2 and 3 versions." }, { "code": null, "e": 1530, "s": 1511, "text": "pip install Scrapy" }, { "code": null, "e": 1533, "s": 1530, "text": "Or" }, { "code": null, "e": 1569, "s": 1533, "text": "conda install –c conda-forge scrapy" }, { "code": null, "e": 1660, "s": 1569, "text": "If Scrapy is installed correctly, a scrapy command will now be available in the terminal −" }, { "code": null, "e": 2299, "s": 1660, "text": "C:\\Users\\rajesh>scrapy\nScrapy 1.6.0 - no active project\n\nUsage:\nscrapy <command> [options] [args]\n\nAvailable commands:\nbench Run quick benchmark test\nfetch Fetch a URL using the Scrapy downloader\ngenspider Generate new spider using pre-defined templates\nrunspider Run a self-contained spider (without creating a project)\nsettings Get settings values\nshell Interactive scraping console\nstartproject Create new project\nversion Print Scrapy version\nview Open URL in browser, as seen by Scrapy\n\n[ more ] More commands available when run from project directory\n\nUse \"scrapy <command> -h\" to see more info about a command." }, { "code": null, "e": 2429, "s": 2299, "text": "Now that Scrapy is installed, we can run the startproject command to generate the default structure for our first Scrapy project." }, { "code": null, "e": 2641, "s": 2429, "text": "To do this, open the terminal and navigate to the directory where you want to store your Scrapy project, and then run scrapy startproject <project name>. Below I'm using the scrapy_example for the project name −" }, { "code": null, "e": 3285, "s": 2641, "text": "C:\\Users\\rajesh>scrapy startproject scrapy_example\nNew Scrapy project 'scrapy_example', using template directory 'c:\\python\\python361\\lib\\site-packages\\scrapy\\templates\\project', created in:\nC:\\Users\\rajesh\\scrapy_example\n\nYou can start your first spider with:\ncd scrapy_example\nscrapy genspider example example.com\n\nC:\\Users\\rajesh>cd scrapy_example\nC:\\Users\\rajesh\\scrapy_example>tree /F\nFolder PATH listing\nVolume serial number is 8CD6-8D39\nC:.\n│ scrapy.cfg\n│\n└───scrapy_example\n │ items.py\n │ middlewares.py\n │ pipelines.py\n │ settings.py\n │ __init__.py\n │\n ├───spiders\n │ │ __init__.py\n │ │\n │ └───__pycache__\n └───__pycache__\n" }, { "code": null, "e": 3359, "s": 3285, "text": "Another way is we run the scrapy shell and do web scrapping, like below −" }, { "code": null, "e": 3508, "s": 3359, "text": "In [18]: fetch (\"https://www.wsj.com/india\")\n019-02-04 22:38:53 [scrapy.core.engine] DEBUG: Crawled (200) https://www.wsj.com/india> (referer: None)" }, { "code": null, "e": 3646, "s": 3508, "text": "The scrapy crawler will return a \"response\" object that contains the downloaded information. Let's check what our above crawler contain −" }, { "code": null, "e": 3684, "s": 3646, "text": "In [19]: view(response)\nOut[19]: True" }, { "code": null, "e": 3768, "s": 3684, "text": "And in your default browser, the web link will open & you will see something like −" }, { "code": null, "e": 3882, "s": 3768, "text": "Great, that looks somewhat similar to our web page, so the crawler has successfully download the entire web page." }, { "code": null, "e": 3920, "s": 3882, "text": "Now let's what our crawler contains −" }, { "code": null, "e": 6897, "s": 3920, "text": "In [22]: print(response.text)\n<!DOCTYPE html>\n<html data-region = \"asia,india\" data-protocol = \"https\" data-reactid = \".2316x0ul96e\" data-react-checksum = \"851122071\">\n <head data-reactid = \".2316x0ul96e.0\">\n <title data-reactid = \".2316x0ul96e.0.0\">The Wall Street Journal & Breaking News, Business, Financial and Economic News, World News and Video</title>\n <meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\" data-reactid = \".2316x0ul96e.0.1\"/>\n <meta http-equiv = \"Content-Type\" content = \"text/html; charset = UTF-8\" data-reactid = \".2316x0ul96e.0.2\"/>\n <meta name = \"viewport\" content = \"initial-scale = 1.0001, minimum-scale = 1.0001, maximum-scale = 1.0001, \n user-scalable = no\" data-reactid = \".2316x0ul96e.0.3\"/>\n <meta name = \"description\" content = \"WSJ online coverage of breaking news and current headlines from the\n US and around the world. Top stories, photos, videos, detailed analysis and in-depth reporting.\" data-reactid = \".2316x0ul96e.0.4\"/>\n <meta name = \"keywords\" content = \"News, breaking news, latest news, US news, headlines, world news, \n business, finances, politics, WSJ, WSJ news, WSJ.com, Wall Street Journal\" data-reactid = \".2316x0ul96e.0.5\"/>\n <meta name = \"page.site\" content = \"wsj\" data-reactid = \".2316x0ul96e.0.7\"/>\n <meta name = \"page.site.product\" content = \"WSJ\" data-reactid = \".2316x0ul96e.0.8\"/>\n <meta name = \"stack.name\" content = \"dj01:vir:prod-sections\" data-reactid = \".2316x0ul96e.0.9\"/>\n <meta name = \"referrer\" content = \"always\" data-reactid = \".2316x0ul96e.0.a\"/>\n <link rel = \"canonical\" href = \"https://www.wsj.com/india/\" data-reactid = \".2316x0ul96e.0.b\"/>\n <meta nameproperty = \"og:url\" content = \"https://www.wsj.com/india/\" data-reactid = \".2316x0ul96e.0.c:$0\"/>\n <meta nameproperty = \"og:title\" content = \"The Wall Street Journal & Breaking News, Business, Financial \n and Economic News, World News and Video\" data-reactid = \".2316x0ul96e.0.c:$1\"/>\n <meta nameproperty = \"og:description\" content = \"WSJ online coverage of breaking news and current \n headlines from the US and around the world. Top stories, photos, videos, detailed analysis and in-depth reporting.\" data-reactid = \".2316x0ul96e.0.c:$2\"/>\n <meta nameproperty = \"og:type\" content = \"website\" data-reactid = \".2316x0ul96e.0.c:$3\"/>\n <meta nameproperty = \"og:site_name\" content = \"The Wall Street Journal\" data-reactid = \".2316x0ul96e.0.c:$4\"/>\n <meta nameproperty = \"og:image\" content = \"https://s.wsj.net/img/meta/wsj-social-share.png\" data-reactid = \".2316x0ul96e.0.c:$5\"/>\n <meta name = \"twitter:site\" content = \"@wsj\" data-reactid = \".2316x0ul96e.0.c:$6\"/>\n <meta name = \"twitter:app:name:iphone\" content = \"The Wall Street Journal\" data-reactid = \".2316x0ul96e.0.c:$7\"/>\n <meta name = \"twitter:app:name:googleplay\" content = \"The Wall Street Journal\" data-reactid = \" \"/>\n...& so much more:" }, { "code": null, "e": 7101, "s": 6897, "text": "Scrapy provides ways to extract information from HTML based on css selectors like class, id etc. To find the css selector for title of any webpage title, simply right click and click inspect, like below:" }, { "code": null, "e": 7164, "s": 7101, "text": "This is will open the developer tools in your browser window −" }, { "code": null, "e": 7381, "s": 7164, "text": "As it can be seen, the css class \"wsj-headline-link\" is applied to all anchor(<a>) tags that have titles. With this information, we'll try to find all the titles from the rest of the contents in the response object −" }, { "code": null, "e": 7560, "s": 7381, "text": "The response.css() is the function that will extract content based on css selector passed to it (like anchor tag above). Let's see some more example of our response.css function." }, { "code": null, "e": 7687, "s": 7560, "text": "In [24]: response.css(\".wsj-headline-link::text\").extract_first()\n\nOut[24]: 'China Fears Loom Over Stocks After January Surge'" }, { "code": null, "e": 7691, "s": 7687, "text": "and" }, { "code": null, "e": 7999, "s": 7691, "text": "In [25]: response.css(\".wsj-headline-link\").extract_first()\n\nOut[25]: '<a class=\"wsj-headline-link\" href = \"https://www.wsj.com/articles/china-fears-loom-over-stocks-after-january-surge-11549276200\" data-reactid=\".2316x0ul96e.1.1.5.1.0.3.3.0.0.0:$0.1.0\">China Fears Loom Over Stocks After January Surge</a>'" }, { "code": null, "e": 8039, "s": 7999, "text": "To get all the links from the webpage −" }, { "code": null, "e": 8087, "s": 8039, "text": "links = response.css('a::attr(href)').extract()" }, { "code": null, "e": 9267, "s": 8087, "text": "['https://www.google.com/intl/en_us/chrome/browser/desktop/index.html',\n'https://support.apple.com/downloads/',\n'https://www.mozilla.org/en-US/firefox/new/',\n'https://windows.microsoft.com/en-us/internet-explorer/download-ie',\n'https://www.barrons.com',\n'http://bigcharts.marketwatch.com',\n'https://www.wsj.com/public/page/wsj-x-marketing.html',\n'https://www.dowjones.com/',\n'https://global.factiva.com/factivalogin/login.asp?productname=global',\n'https://www.fnlondon.com/',\n'https://www.mansionglobal.com/',\n'https://www.marketwatch.com',\n'https://newsplus.wsj.com',\n'https://privatemarkets.dowjones.com',\n'https://djlogin.dowjones.com/login.asp?productname=rnc',\n'https://www.wsj.com/conferences',\n'https://www.wsj.com/pro/centralbanking',\n'https://www.wsj.com/video/',\n'https://www.wsj.com',\n'http://www.bigdecisions.com/',\n'https://www.businessspectator.com.au/',\n'https://www.checkout51.com/?utm_source=wsj&utm_medium=digitalhousead&utm_campaign=wsjspotlight',\n'https://www.harpercollins.com/',\n'https://housing.com/',\n'https://www.makaan.com/',\n'https://nypost.com/',\n'https://www.newsamerica.com/',\n'https://www.proptiger.com',\n'https://www.rea-group.com/',\n......\n......" }, { "code": null, "e": 9336, "s": 9267, "text": "To get the comment count from the wsj(wall street journel) webpage −" }, { "code": null, "e": 9419, "s": 9336, "text": "In [38]: response.css(\".wsj-comment-count::text\").extract()\n\nOut[38]: ['71', '59']" }, { "code": null, "e": 9514, "s": 9419, "text": "Above is just the introduction to web-scraping through scrapy, we can do lot more with scrapy." } ]
Python program to determine if the given IP Address is Public or Private using ipaddress module
10 Jul, 2020 Given a Classful IP Address the task is to find whether it is Public or Private. Private IP address of a system is the IP address which is used to communicate within the same network. Using private IP data or information can be sent or received within the same network. Public IP address of a system is the IP address which is used to communicate outside the network. Public IP address is basically assigned by the ISP (Internet Service Provider). Examples: Input : 17.5.7.8 Output : Public Input : 172.16.0.10 Output : Private To implement it, we will use is_private method of ipaddress module of Python 3.3 . # importing ip_address from # ip address modulefrom ipaddress import ip_address def IPAddress(IP: str) -> str: return "Private" if (ip_address(IP).is_private) else "Public" if __name__ == '__main__' : # Public IP print(IPAddress('17.5.7.8')) # Private IP print(IPAddress('172.16.0.10')) Output : Public Private python-utility Python Python Programs 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 109, "s": 28, "text": "Given a Classful IP Address the task is to find whether it is Public or Private." }, { "code": null, "e": 298, "s": 109, "text": "Private IP address of a system is the IP address which is used to communicate within the same network. Using private IP data or information can be sent or received within the same network." }, { "code": null, "e": 476, "s": 298, "text": "Public IP address of a system is the IP address which is used to communicate outside the network. Public IP address is basically assigned by the ISP (Internet Service Provider)." }, { "code": null, "e": 486, "s": 476, "text": "Examples:" }, { "code": null, "e": 558, "s": 486, "text": "Input : 17.5.7.8\nOutput : Public\n\nInput : 172.16.0.10\nOutput : Private\n" }, { "code": null, "e": 641, "s": 558, "text": "To implement it, we will use is_private method of ipaddress module of Python 3.3 ." }, { "code": "# importing ip_address from # ip address modulefrom ipaddress import ip_address def IPAddress(IP: str) -> str: return \"Private\" if (ip_address(IP).is_private) else \"Public\" if __name__ == '__main__' : # Public IP print(IPAddress('17.5.7.8')) # Private IP print(IPAddress('172.16.0.10'))", "e": 957, "s": 641, "text": null }, { "code": null, "e": 966, "s": 957, "text": "Output :" }, { "code": null, "e": 981, "s": 966, "text": "Public\nPrivate" }, { "code": null, "e": 996, "s": 981, "text": "python-utility" }, { "code": null, "e": 1003, "s": 996, "text": "Python" }, { "code": null, "e": 1019, "s": 1003, "text": "Python Programs" }, { "code": null, "e": 1117, "s": 1019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1149, "s": 1117, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1176, "s": 1149, "text": "Python Classes and Objects" }, { "code": null, "e": 1197, "s": 1176, "text": "Python OOPs Concepts" }, { "code": null, "e": 1220, "s": 1197, "text": "Introduction To PYTHON" }, { "code": null, "e": 1276, "s": 1220, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1298, "s": 1276, "text": "Defaultdict in Python" }, { "code": null, "e": 1337, "s": 1298, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1375, "s": 1337, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1412, "s": 1375, "text": "Python Program for Fibonacci numbers" } ]
bzip2 - Unix, Linux Command
bzip2 - To compress or decompress named file(s). bzip2 [ -cdfkqstvzVL123456789 ] [ filenames ... ] Compared with gzip, bzip2 creates smaller archives but has a slower decompression time and higher memory use. bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding. The command-line options provided are deliberately very similar to those of GNU gzip, but they are not identical. bzip2 expects a list of file names along with the command-line flags. Each file is replaced by a compressed version of itself, with the name original_name.bz2. Each compressed file has the same modification date, permissions, and, when possible, ownership as the corresponding original, so that these properties can be correctly restored at decompression time. File name handling is naive in the sense that there is no mechanism for preserving original file names, permissions, ownerships or dates in filesystems which lack these concepts, or have serious file name length restrictions, such as MS-DOS. bzip2 and bunzip2 by default will not overwrite existing files. To overwrite, specify the -f flag. To compress the file sample.txt and replace it with a compressed version named sample.txt.bz2 $ bzip2 sample.txt $ ls sample.txt.bz2 To compress the file sample.txt, keep the uncompressed version and create the new file. $ bzip2 -k sample.txt $ ls sample.txt sample.txt.bz2 To combine a set of mp3 music files into one file with tar and then zip the result with bzip2. $ tar -cf music.tar 1.mp3 2.mp3 3.mp3 $ bzip2 music.tar $ ls 1.mp3 2.mp3 3.mp3 music.tar.bz2 To combine a set of mp3 music files into one file with tar and then zip the result with bzip2 in single command. $ tar -cjf music.tar.bz2 miles.mp3 chet.mp3 charlie.mp3 $ ls music.tar.bz2 miles.mp3 chet.mp3 charlie.mp3
[ { "code": null, "e": 10760, "s": 10711, "text": "bzip2 - To compress or decompress named file(s)." }, { "code": null, "e": 10810, "s": 10760, "text": "bzip2 [ -cdfkqstvzVL123456789 ] [ filenames ... ]" }, { "code": null, "e": 11506, "s": 10810, "text": "Compared with gzip, bzip2 creates smaller archives but has a slower decompression time and higher memory use. bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding. The command-line options provided are deliberately very similar to those of GNU gzip, but they are not identical. bzip2 expects a list of file names along with the command-line flags. Each file is replaced by a compressed version of itself, with the name original_name.bz2. Each compressed file has the same modification date, permissions, and, when possible, ownership as the corresponding original, so that these properties can be correctly restored at decompression time." }, { "code": null, "e": 11848, "s": 11506, "text": "File name handling is naive in the sense that there is no mechanism for preserving original file names, permissions, ownerships or dates in filesystems which lack these concepts, or have serious file name length restrictions, such as MS-DOS. bzip2 and bunzip2 by default will not overwrite existing files. To overwrite, specify the -f flag. " }, { "code": null, "e": 11942, "s": 11848, "text": "To compress the file sample.txt and replace it with a compressed version named sample.txt.bz2" }, { "code": null, "e": 11982, "s": 11942, "text": "$ bzip2 sample.txt\n$ ls\nsample.txt.bz2\n" }, { "code": null, "e": 12070, "s": 11982, "text": "To compress the file sample.txt, keep the uncompressed version and create the new file." }, { "code": null, "e": 12124, "s": 12070, "text": "$ bzip2 -k sample.txt\n$ ls\nsample.txt sample.txt.bz2\n" }, { "code": null, "e": 12219, "s": 12124, "text": "To combine a set of mp3 music files into one file with tar and then zip the result with bzip2." }, { "code": null, "e": 12313, "s": 12219, "text": "$ tar -cf music.tar 1.mp3 2.mp3 3.mp3\n$ bzip2 music.tar\n$ ls\n1.mp3 2.mp3 3.mp3 music.tar.bz2\n" }, { "code": null, "e": 12426, "s": 12313, "text": "To combine a set of mp3 music files into one file with tar and then zip the result with bzip2 in single command." } ]
MongoDB – Backup and Restoration
08 Mar, 2021 Data backup is one of the most highly required processes for any database management system as data can be lost or get corrupted to overcome these drawbacks we need database backup. Database backup is a copy of a database that already exists. In MongoDB, mongodump tool is used to take the data backup. And mongorestore tool is used to restore the backup data. In MongoDB, mongodump tool is used to take the data backup. It simply dumps all the data stored into a dump directory of MongoDB. Backed-up data is in BSON format also known as BSON data dumps. By default, the backup is stored in mongodb’s bin\dump folder to specify a different output directory we can use the –out option. Mongodump is used in two ways with or without argument. Without Argument: Without any arguments, mongodump connects with MongoDB instance on the local system on port 27017 and creates a backup of every database and every collection. mongodump With Argument: By specifying the database in the argument by which we can limit the amount of data stored in the database dump mongodump --db databaseName --collection collectionName To specify a different output directory we can use the –out option: mongodump –db databaseName –collection collectionName –out c:\backup Example 1: Backing up all the databases Here we have 10 databases which all get backed up in the folder backupDatabase. Note– exit mongo shell by ctrl+c to use the mongodump command. mongodump --out c:\backupDatabase Example 2: Backing up the specified collection Here, we are making a backup of the collection student which contains 6 documents and is inside the GeeksForGeeks database, the backup is made inside the GFGbackup Folder. mongodump –db GeeksForGeeks –collection students –out c:\GFGbackup In MongoDB, mongorestore utility is used to restore the backup data. It restores the binary backup created by mongodump utility(i.e., BSON data dumps). It can restore either an entire database backup or a subset of the backup. It also restores the indexes which are created for any collection inside that database. By default, mongorestore looks for a database backup in mongodb’s bin\dump folder which is also the default folder for mongodump command for dumping the backup. To restore all the database use – mongorestore dump To restore a specific collection use- mongorestore –db databaseName –collection collectionName directory\collectionName.bson Example: In this example, we are using a database GeeksForGeeks which has 4 collections. We are firstly going to make a backup of student collection and then drop the student collection and then restore the student collection. To make backup we use – mongodump --db GeeksForGeeks --collection students --out c:\GFGbackup The backup will be stored in c:\GFGbackup folder Now we will drop students collection by using- db.students.drop() Now we will restore student collection by using – mongorestore –db GeeksForGeeks –collection students c:\GFGbackup\GeeksForGeeks\students.bson MongoDB Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Regex MongoDB - Compound Indexes MongoDB updateMany() Method - db.Collection.updateMany() MongoDB Cursor Spring Boot - CRUD Operations using MongoDB
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Mar, 2021" }, { "code": null, "e": 390, "s": 28, "text": "Data backup is one of the most highly required processes for any database management system as data can be lost or get corrupted to overcome these drawbacks we need database backup. Database backup is a copy of a database that already exists. In MongoDB, mongodump tool is used to take the data backup. And mongorestore tool is used to restore the backup data. " }, { "code": null, "e": 770, "s": 390, "text": "In MongoDB, mongodump tool is used to take the data backup. It simply dumps all the data stored into a dump directory of MongoDB. Backed-up data is in BSON format also known as BSON data dumps. By default, the backup is stored in mongodb’s bin\\dump folder to specify a different output directory we can use the –out option. Mongodump is used in two ways with or without argument." }, { "code": null, "e": 788, "s": 770, "text": "Without Argument:" }, { "code": null, "e": 948, "s": 788, "text": "Without any arguments, mongodump connects with MongoDB instance on the local system on port 27017 and creates a backup of every database and every collection. " }, { "code": null, "e": 958, "s": 948, "text": "mongodump" }, { "code": null, "e": 974, "s": 958, "text": "With Argument: " }, { "code": null, "e": 1086, "s": 974, "text": "By specifying the database in the argument by which we can limit the amount of data stored in the database dump" }, { "code": null, "e": 1142, "s": 1086, "text": "mongodump --db databaseName --collection collectionName" }, { "code": null, "e": 1210, "s": 1142, "text": "To specify a different output directory we can use the –out option:" }, { "code": null, "e": 1279, "s": 1210, "text": "mongodump –db databaseName –collection collectionName –out c:\\backup" }, { "code": null, "e": 1319, "s": 1279, "text": "Example 1: Backing up all the databases" }, { "code": null, "e": 1399, "s": 1319, "text": "Here we have 10 databases which all get backed up in the folder backupDatabase." }, { "code": null, "e": 1462, "s": 1399, "text": "Note– exit mongo shell by ctrl+c to use the mongodump command." }, { "code": null, "e": 1496, "s": 1462, "text": "mongodump --out c:\\backupDatabase" }, { "code": null, "e": 1543, "s": 1496, "text": "Example 2: Backing up the specified collection" }, { "code": null, "e": 1715, "s": 1543, "text": "Here, we are making a backup of the collection student which contains 6 documents and is inside the GeeksForGeeks database, the backup is made inside the GFGbackup Folder." }, { "code": null, "e": 1783, "s": 1715, "text": "mongodump –db GeeksForGeeks –collection students –out c:\\GFGbackup " }, { "code": null, "e": 2259, "s": 1783, "text": "In MongoDB, mongorestore utility is used to restore the backup data. It restores the binary backup created by mongodump utility(i.e., BSON data dumps). It can restore either an entire database backup or a subset of the backup. It also restores the indexes which are created for any collection inside that database. By default, mongorestore looks for a database backup in mongodb’s bin\\dump folder which is also the default folder for mongodump command for dumping the backup." }, { "code": null, "e": 2293, "s": 2259, "text": "To restore all the database use –" }, { "code": null, "e": 2311, "s": 2293, "text": "mongorestore dump" }, { "code": null, "e": 2349, "s": 2311, "text": "To restore a specific collection use-" }, { "code": null, "e": 2437, "s": 2349, "text": "mongorestore –db databaseName –collection collectionName directory\\collectionName.bson" }, { "code": null, "e": 2446, "s": 2437, "text": "Example:" }, { "code": null, "e": 2664, "s": 2446, "text": "In this example, we are using a database GeeksForGeeks which has 4 collections. We are firstly going to make a backup of student collection and then drop the student collection and then restore the student collection." }, { "code": null, "e": 2688, "s": 2664, "text": "To make backup we use –" }, { "code": null, "e": 2759, "s": 2688, "text": "mongodump --db GeeksForGeeks --collection students --out c:\\GFGbackup " }, { "code": null, "e": 2808, "s": 2759, "text": "The backup will be stored in c:\\GFGbackup folder" }, { "code": null, "e": 2855, "s": 2808, "text": "Now we will drop students collection by using-" }, { "code": null, "e": 2875, "s": 2855, "text": "db.students.drop() " }, { "code": null, "e": 2925, "s": 2875, "text": "Now we will restore student collection by using –" }, { "code": null, "e": 3020, "s": 2925, "text": "mongorestore –db GeeksForGeeks –collection students c:\\GFGbackup\\GeeksForGeeks\\students.bson " }, { "code": null, "e": 3028, "s": 3020, "text": "MongoDB" }, { "code": null, "e": 3035, "s": 3028, "text": "Picked" }, { "code": null, "e": 3043, "s": 3035, "text": "MongoDB" }, { "code": null, "e": 3141, "s": 3043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3179, "s": 3141, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 3204, "s": 3179, "text": "MongoDB - limit() Method" }, { "code": null, "e": 3228, "s": 3204, "text": "MongoDB - sort() Method" }, { "code": null, "e": 3255, "s": 3228, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 3310, "s": 3255, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 3326, "s": 3310, "text": "MongoDB - Regex" }, { "code": null, "e": 3353, "s": 3326, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 3410, "s": 3353, "text": "MongoDB updateMany() Method - db.Collection.updateMany()" }, { "code": null, "e": 3425, "s": 3410, "text": "MongoDB Cursor" } ]
PHP Tutorial
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP. PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994. PHP is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning PHP: PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time. PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time. PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. PHP is forgiving: PHP language tries to be as forgiving as possible. PHP is forgiving: PHP language tries to be as forgiving as possible. PHP Syntax is C-Like. PHP Syntax is C-Like. Five important characteristics make PHP's practical nature possible − Simplicity Efficiency Security Flexibility Familiarity Just to give you a little excitement about PHP, I'm going to give you a small conventional PHP Hello World program, You can try it using Demo link. <html> <head> <title>Hello World</title> </head> <body> <?php echo "Hello, World!";?> </body> </html> As mentioned before, PHP is one of the most widely used language over the web. I'm going to list few of them here: PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them. PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them. PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user. PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user. You add, delete, modify elements within your database through PHP. You add, delete, modify elements within your database through PHP. Access cookies variables and set cookies. Access cookies variables and set cookies. Using PHP, you can restrict users to access some pages of your website. Using PHP, you can restrict users to access some pages of your website. It can encrypt data. It can encrypt data. This PHP tutorial is designed for PHP programmers who are completely unaware of PHP concepts but they have basic understanding on computer programming. Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful.
[ { "code": null, "e": 3161, "s": 2891, "text": "The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP." }, { "code": null, "e": 3342, "s": 3161, "text": "PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994." }, { "code": null, "e": 3551, "s": 3342, "text": "PHP is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning PHP:" }, { "code": null, "e": 3613, "s": 3551, "text": "PHP is a recursive acronym for \"PHP: Hypertext Preprocessor\"." }, { "code": null, "e": 3675, "s": 3613, "text": "PHP is a recursive acronym for \"PHP: Hypertext Preprocessor\"." }, { "code": null, "e": 3844, "s": 3675, "text": "PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites." }, { "code": null, "e": 4013, "s": 3844, "text": "PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites." }, { "code": null, "e": 4147, "s": 4013, "text": "It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server." }, { "code": null, "e": 4281, "s": 4147, "text": "It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server." }, { "code": null, "e": 4499, "s": 4281, "text": "PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time." }, { "code": null, "e": 4717, "s": 4499, "text": "PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time." }, { "code": null, "e": 4936, "s": 4717, "text": "PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time." }, { "code": null, "e": 5155, "s": 4936, "text": "PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time." }, { "code": null, "e": 5224, "s": 5155, "text": "PHP is forgiving: PHP language tries to be as forgiving as possible." }, { "code": null, "e": 5293, "s": 5224, "text": "PHP is forgiving: PHP language tries to be as forgiving as possible." }, { "code": null, "e": 5315, "s": 5293, "text": "PHP Syntax is C-Like." }, { "code": null, "e": 5337, "s": 5315, "text": "PHP Syntax is C-Like." }, { "code": null, "e": 5407, "s": 5337, "text": "Five important characteristics make PHP's practical nature possible −" }, { "code": null, "e": 5418, "s": 5407, "text": "Simplicity" }, { "code": null, "e": 5429, "s": 5418, "text": "Efficiency" }, { "code": null, "e": 5438, "s": 5429, "text": "Security" }, { "code": null, "e": 5450, "s": 5438, "text": "Flexibility" }, { "code": null, "e": 5462, "s": 5450, "text": "Familiarity" }, { "code": null, "e": 5610, "s": 5462, "text": "Just to give you a little excitement about PHP, I'm going to give you a small conventional PHP Hello World program, You can try it using Demo link." }, { "code": null, "e": 5745, "s": 5610, "text": "<html>\n \n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <?php echo \"Hello, World!\";?>\n </body>\n\n</html>" }, { "code": null, "e": 5860, "s": 5745, "text": "As mentioned before, PHP is one of the most widely used language over the web. I'm going to list few of them here:" }, { "code": null, "e": 5969, "s": 5860, "text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them." }, { "code": null, "e": 6078, "s": 5969, "text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them." }, { "code": null, "e": 6208, "s": 6078, "text": "PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user." }, { "code": null, "e": 6338, "s": 6208, "text": "PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user." }, { "code": null, "e": 6405, "s": 6338, "text": "You add, delete, modify elements within your database through PHP." }, { "code": null, "e": 6472, "s": 6405, "text": "You add, delete, modify elements within your database through PHP." }, { "code": null, "e": 6514, "s": 6472, "text": "Access cookies variables and set cookies." }, { "code": null, "e": 6556, "s": 6514, "text": "Access cookies variables and set cookies." }, { "code": null, "e": 6628, "s": 6556, "text": "Using PHP, you can restrict users to access some pages of your website." }, { "code": null, "e": 6700, "s": 6628, "text": "Using PHP, you can restrict users to access some pages of your website." }, { "code": null, "e": 6721, "s": 6700, "text": "It can encrypt data." }, { "code": null, "e": 6742, "s": 6721, "text": "It can encrypt data." }, { "code": null, "e": 6894, "s": 6742, "text": "This PHP tutorial is designed for PHP programmers who are completely unaware of PHP concepts but they have basic understanding on computer programming." } ]
How to apply CSS style using jQuery ?
20 Sep, 2021 In this article, we will explore how we can apply CSS styles to HTML elements. It is recommended that you have some basic knowledge of HTML, CSS, JavaScript, and jQuery before beginning this article. It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. Syntax: $().css(propertyname, value); $().css(properties); There are many types of CSS methods, which means that each method has the same name but takes different parameters. We will discuss only two methods, one of which is used to change a single CSS property, while the other is used to change multiple CSS properties simultaneously. With the second method, you can pass a JSON string object as a parameter that you want to apply to the HTML element. JSON string objects contain CSS properties along with their values, and the first method only takes 2 parameters, namely the property name and the value. Example: By clicking the button, it adds multiple CSS properties to the selected element, but by double-clicking the button, it adds only one CSS property. The motive of this example is to show the use of two types of CSS methods which are discussed. HTML <!DOCTYPE html><html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script></head> <body style="text-align: center; border: 2px solid green; min-height: 240px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="context"> Hello Geeks!! welcome to geeksforgeeks </p> <br> <button id="change"> clickme </button> <script> let css_property = { "color": "green", "font-size": "20px" } $('#change').on('click', function () { // For multiple css property $('#context').css(css_property); }); $('#change').on('dblclick', function () { // For single css property $('#context').css('display', 'none'); }) </script></body> </html> Output: output Blogathon-2021 jQuery-Methods jQuery-Questions Picked Blogathon HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Sep, 2021" }, { "code": null, "e": 228, "s": 28, "text": "In this article, we will explore how we can apply CSS styles to HTML elements. It is recommended that you have some basic knowledge of HTML, CSS, JavaScript, and jQuery before beginning this article." }, { "code": null, "e": 385, "s": 228, "text": "It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. " }, { "code": null, "e": 393, "s": 385, "text": "Syntax:" }, { "code": null, "e": 444, "s": 393, "text": "$().css(propertyname, value);\n$().css(properties);" }, { "code": null, "e": 840, "s": 444, "text": "There are many types of CSS methods, which means that each method has the same name but takes different parameters. We will discuss only two methods, one of which is used to change a single CSS property, while the other is used to change multiple CSS properties simultaneously. With the second method, you can pass a JSON string object as a parameter that you want to apply to the HTML element. " }, { "code": null, "e": 994, "s": 840, "text": "JSON string objects contain CSS properties along with their values, and the first method only takes 2 parameters, namely the property name and the value." }, { "code": null, "e": 1246, "s": 994, "text": "Example: By clicking the button, it adds multiple CSS properties to the selected element, but by double-clicking the button, it adds only one CSS property. The motive of this example is to show the use of two types of CSS methods which are discussed. " }, { "code": null, "e": 1251, "s": 1246, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script></head> <body style=\"text-align: center; border: 2px solid green; min-height: 240px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"context\"> Hello Geeks!! welcome to geeksforgeeks </p> <br> <button id=\"change\"> clickme </button> <script> let css_property = { \"color\": \"green\", \"font-size\": \"20px\" } $('#change').on('click', function () { // For multiple css property $('#context').css(css_property); }); $('#change').on('dblclick', function () { // For single css property $('#context').css('display', 'none'); }) </script></body> </html>", "e": 2123, "s": 1251, "text": null }, { "code": null, "e": 2131, "s": 2123, "text": "Output:" }, { "code": null, "e": 2138, "s": 2131, "text": "output" }, { "code": null, "e": 2153, "s": 2138, "text": "Blogathon-2021" }, { "code": null, "e": 2168, "s": 2153, "text": "jQuery-Methods" }, { "code": null, "e": 2185, "s": 2168, "text": "jQuery-Questions" }, { "code": null, "e": 2192, "s": 2185, "text": "Picked" }, { "code": null, "e": 2202, "s": 2192, "text": "Blogathon" }, { "code": null, "e": 2207, "s": 2202, "text": "HTML" }, { "code": null, "e": 2214, "s": 2207, "text": "JQuery" }, { "code": null, "e": 2231, "s": 2214, "text": "Web Technologies" }, { "code": null, "e": 2236, "s": 2231, "text": "HTML" }, { "code": null, "e": 2334, "s": 2236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2375, "s": 2334, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 2413, "s": 2375, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 2457, "s": 2413, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 2517, "s": 2457, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 2584, "s": 2517, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 2632, "s": 2584, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2694, "s": 2632, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2744, "s": 2694, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2768, "s": 2744, "text": "REST API (Introduction)" } ]
math.modf() function in Lua programming
There are several occurrences when we want to get the integer value of a number and also the fractional value that the number has if any, so that we can use either or both of these values. Lua provides us with a math.modf() function that we can use to find the integer value along with the fractional value if the number has any. math.modf(number) The math.modf() function returns two values when we call the function, the first value is the integer value of the number and the second returned value is the fractional value of the number if it has any. Let’s consider a simple example where we will make use of the math.modf() function in Lua − Live Demo a, b = math.modf(3.3) c, d = math.modf(7.1) print(a, b) print(c, d) 3 0.3 7 0.1 It should be noted that if we try to find modf of a number which is already the closest integer to itself then we will get the same number as the output. Consider the example shown below − Live Demo e, f = math.modf(8) print(e, f) 8 0.0 We can also pass negative numbers in the math.modf() function as an argument. Consider the example shown below − Live Demo g, h = math.modf(-3.3) print(g, h) -3 -0.3
[ { "code": null, "e": 1376, "s": 1187, "text": "There are several occurrences when we want to get the integer value of a number and also the fractional value that the number has if any, so that we can use either or both of these values." }, { "code": null, "e": 1517, "s": 1376, "text": "Lua provides us with a math.modf() function that we can use to find the integer value along with the fractional value if the number has any." }, { "code": null, "e": 1535, "s": 1517, "text": "math.modf(number)" }, { "code": null, "e": 1740, "s": 1535, "text": "The math.modf() function returns two values when we call the function, the first value is the integer value of the number and the second returned value is the fractional value of the number if it has any." }, { "code": null, "e": 1832, "s": 1740, "text": "Let’s consider a simple example where we will make use of the math.modf() function in Lua −" }, { "code": null, "e": 1843, "s": 1832, "text": " Live Demo" }, { "code": null, "e": 1911, "s": 1843, "text": "a, b = math.modf(3.3)\nc, d = math.modf(7.1)\nprint(a, b)\nprint(c, d)" }, { "code": null, "e": 1929, "s": 1911, "text": "3 0.3\n7 0.1" }, { "code": null, "e": 2083, "s": 1929, "text": "It should be noted that if we try to find modf of a number which is already the closest integer to itself then we will get the same number as the output." }, { "code": null, "e": 2118, "s": 2083, "text": "Consider the example shown below −" }, { "code": null, "e": 2129, "s": 2118, "text": " Live Demo" }, { "code": null, "e": 2161, "s": 2129, "text": "e, f = math.modf(8)\nprint(e, f)" }, { "code": null, "e": 2171, "s": 2161, "text": "8 0.0" }, { "code": null, "e": 2249, "s": 2171, "text": "We can also pass negative numbers in the math.modf() function as an argument." }, { "code": null, "e": 2284, "s": 2249, "text": "Consider the example shown below −" }, { "code": null, "e": 2295, "s": 2284, "text": " Live Demo" }, { "code": null, "e": 2330, "s": 2295, "text": "g, h = math.modf(-3.3)\nprint(g, h)" }, { "code": null, "e": 2341, "s": 2330, "text": "-3 -0.3" } ]
Node.js - Environment Setup
You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options. Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) − /* Hello World! program in Node.js */ console.log("Hello World!"); For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning. If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables. This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension ".js". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it. The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code. Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. Following section guides you on how to install Node.js binary distribution on various OS. Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS. Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v6.3.1-linux-x64/* /usr/local/nodejs Add /usr/local/nodejs/bin to the PATH environment variable. Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejs\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect. Create a js file named main.js on your machine (Windows or Linux) having the following code. /* Hello, World! program in node.js */ console.log("Hello, World!") Now execute main.js file using Node.js interpreter to see the result − $ node main.js If everything is fine with your installation, this should produce the following result −
[ { "code": null, "e": 2471, "s": 2152, "text": "You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the available examples online and learn through practice. Feel free to modify any example and check the results with different options." }, { "code": null, "e": 2606, "s": 2471, "text": "Try the following example using the Live Demo option available at the top right corner of the below sample code box (on our website) −" }, { "code": null, "e": 2673, "s": 2606, "text": "/* Hello World! program in Node.js */\nconsole.log(\"Hello World!\");" }, { "code": null, "e": 2801, "s": 2673, "text": "For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning." }, { "code": null, "e": 2988, "s": 2801, "text": "If you are still willing to set up your environment for Node.js, you need the following two softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables." }, { "code": null, "e": 3132, "s": 2988, "text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 3314, "s": 3132, "text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX." }, { "code": null, "e": 3493, "s": 3314, "text": "The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension \".js\"." }, { "code": null, "e": 3674, "s": 3493, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it." }, { "code": null, "e": 3819, "s": 3674, "text": "The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code." }, { "code": null, "e": 4000, "s": 3819, "text": "Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. " }, { "code": null, "e": 4090, "s": 4000, "text": "Following section guides you on how to install Node.js binary distribution on various OS." }, { "code": null, "e": 4267, "s": 4090, "text": "Download latest version of Node.js installable archive file from Node.js Downloads. At the time of writing this tutorial, following are the versions available on different OS." }, { "code": null, "e": 4453, "s": 4267, "text": "Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example:" }, { "code": null, "e": 4646, "s": 4453, "text": "$ cd /tmp\n$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz\n$ tar xvfz node-v6.3.1-linux-x64.tar.gz\n$ mkdir -p /usr/local/nodejs\n$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs\n" }, { "code": null, "e": 4706, "s": 4646, "text": "Add /usr/local/nodejs/bin to the PATH environment variable." }, { "code": null, "e": 5024, "s": 4706, "text": "Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\\Program Files\\nodejs. The installer should set the C:\\Program Files\\nodejs\\bin directory in window's PATH environment variable. Restart any open command prompts for the change to take effect." }, { "code": null, "e": 5117, "s": 5024, "text": "Create a js file named main.js on your machine (Windows or Linux) having the following code." }, { "code": null, "e": 5185, "s": 5117, "text": "/* Hello, World! program in node.js */\nconsole.log(\"Hello, World!\")" }, { "code": null, "e": 5256, "s": 5185, "text": "Now execute main.js file using Node.js interpreter to see the result −" }, { "code": null, "e": 5271, "s": 5256, "text": "$ node main.js" } ]
Reason of runtime error in C/C++
08 Feb, 2021 In this article, we will discuss the reason for the run-time error and its solution. Runtime Error: A runtime error in a program is an error that occurs while the program is running after being successfully compiled. Below are some methods to identify the reason behind Runtime error: Method 1: When the index of the array is assigned with a negative index it leads to invalid memory access during runtime error. Below is the C++ Program to illustrate the invalid memory access during run-time: C++ // C++ program to illustrate invalid// memory access during run-time#include <iostream>using namespace std; // Global declarationint arr[5]; // Driver Codeint main(){ int answer = arr[-10]; cout << answer; return 0;} 1736487104 Method 2: Sometimes Array or vector runs out of bound of their limits resulting in a runtime error. Below is the C++ program illustrating array runs out of bound: C++ // C++ program to illustrate// array runs out of bound#include <iostream>using namespace std; // Driver Codeint main(){ long n; n = 100000000000; // 'n' is out of bound for // the array limit long a[n]; cout << a[1] << " "; return 0;} Output: Explanation: This is an error for index out of bound. It can be resolved by using the size of the array/vector as within the limit. Method 3: Some silly mistakes encountered while coding in hurry, sometimes leads to runtime error. Below is the C++ program illustrating runtime error by un-assigned variables: C++ // C++ program to illustrate runtime// error by un-assigned variables#include <iostream>using namespace std; // Driver Codeint main(){ long long N; // N is assigned garbage value long arr[N]; cin >> N; for (int i = 0; i < N; i++) { cin >> arr[i]; } for (int i = 0; i < N; i++) { cout << arr[i] << " "; } return 0;} Output: Explanation: The above program shows “Bad memory access (SIGBUS)” because: Here, variable N is assigned a garbage value resulting in a runtime error. Sometimes, since it depends on the compiler how it assigned the garbage value. This can be resolved by declaring arr[N] after scanning the value for variable n and checking if it is the upper or lower limit of the array/vector index. CPP-Basics C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Feb, 2021" }, { "code": null, "e": 137, "s": 52, "text": "In this article, we will discuss the reason for the run-time error and its solution." }, { "code": null, "e": 337, "s": 137, "text": "Runtime Error: A runtime error in a program is an error that occurs while the program is running after being successfully compiled. Below are some methods to identify the reason behind Runtime error:" }, { "code": null, "e": 547, "s": 337, "text": "Method 1: When the index of the array is assigned with a negative index it leads to invalid memory access during runtime error. Below is the C++ Program to illustrate the invalid memory access during run-time:" }, { "code": null, "e": 551, "s": 547, "text": "C++" }, { "code": "// C++ program to illustrate invalid// memory access during run-time#include <iostream>using namespace std; // Global declarationint arr[5]; // Driver Codeint main(){ int answer = arr[-10]; cout << answer; return 0;}", "e": 781, "s": 551, "text": null }, { "code": null, "e": 793, "s": 781, "text": "1736487104\n" }, { "code": null, "e": 956, "s": 793, "text": "Method 2: Sometimes Array or vector runs out of bound of their limits resulting in a runtime error. Below is the C++ program illustrating array runs out of bound:" }, { "code": null, "e": 960, "s": 956, "text": "C++" }, { "code": "// C++ program to illustrate// array runs out of bound#include <iostream>using namespace std; // Driver Codeint main(){ long n; n = 100000000000; // 'n' is out of bound for // the array limit long a[n]; cout << a[1] << \" \"; return 0;}", "e": 1221, "s": 960, "text": null }, { "code": null, "e": 1229, "s": 1221, "text": "Output:" }, { "code": null, "e": 1242, "s": 1229, "text": "Explanation:" }, { "code": null, "e": 1283, "s": 1242, "text": "This is an error for index out of bound." }, { "code": null, "e": 1361, "s": 1283, "text": "It can be resolved by using the size of the array/vector as within the limit." }, { "code": null, "e": 1538, "s": 1361, "text": "Method 3: Some silly mistakes encountered while coding in hurry, sometimes leads to runtime error. Below is the C++ program illustrating runtime error by un-assigned variables:" }, { "code": null, "e": 1542, "s": 1538, "text": "C++" }, { "code": "// C++ program to illustrate runtime// error by un-assigned variables#include <iostream>using namespace std; // Driver Codeint main(){ long long N; // N is assigned garbage value long arr[N]; cin >> N; for (int i = 0; i < N; i++) { cin >> arr[i]; } for (int i = 0; i < N; i++) { cout << arr[i] << \" \"; } return 0;}", "e": 1909, "s": 1542, "text": null }, { "code": null, "e": 1917, "s": 1909, "text": "Output:" }, { "code": null, "e": 1930, "s": 1917, "text": "Explanation:" }, { "code": null, "e": 1992, "s": 1930, "text": "The above program shows “Bad memory access (SIGBUS)” because:" }, { "code": null, "e": 2067, "s": 1992, "text": "Here, variable N is assigned a garbage value resulting in a runtime error." }, { "code": null, "e": 2146, "s": 2067, "text": "Sometimes, since it depends on the compiler how it assigned the garbage value." }, { "code": null, "e": 2301, "s": 2146, "text": "This can be resolved by declaring arr[N] after scanning the value for variable n and checking if it is the upper or lower limit of the array/vector index." }, { "code": null, "e": 2312, "s": 2301, "text": "CPP-Basics" }, { "code": null, "e": 2316, "s": 2312, "text": "C++" }, { "code": null, "e": 2329, "s": 2316, "text": "C++ Programs" }, { "code": null, "e": 2333, "s": 2329, "text": "CPP" } ]
Storage for Strings in C
16 Jul, 2021 In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C char str[4] = "GfG"; /*One extra for string terminator*//* OR */char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */ When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then string is stored in stack segment, if it’s a global or static variable then stored in data segment, etc. Strings using character pointers Using character pointer strings can be stored in two ways: 1) Read only string in a shared segment. When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read-only block (generally in data segment) that is shared among functions. C char *str = "GfG"; In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in the program. 2) Dynamically allocated in heap segment. Strings are stored like other dynamically allocated things in C and can be shared among functions. C char *str;int size = 4; /*one extra for ‘\0’*/str = (char *)malloc(sizeof(char)*size);*(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\0'; Let us see some examples to better understand the above ways to store strings. Example 1 (Try to modify string) The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory. C int main(){ char *str; str = "GfG"; /* Stored in read only part of data segment */ *(str+1) = 'n'; /* Problem: trying to modify read only memory */ getchar(); return 0;} The below program works perfectly fine as str[] is stored in writable stack segment. C int main(){ char str[] = "GfG"; /* Stored in stack segment like other auto variables */ *(str+1) = 'n'; /* No problem: String is now GnG */ getchar(); return 0;} Below program also works perfectly fine as data at str is stored in writable heap segment. C int main(){ int size = 4; /* Stored in heap segment like other dynamically allocated things */ char *str = (char *)malloc(sizeof(char)*size); *(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\0'; *(str+1) = 'n'; /* No problem: String is now GnG */ getchar(); return 0;} Example 2 (Try to return string from a function) The below program works perfectly fine as the string is stored in a shared segment and data stored remains there even after return of getString() C char *getString(){ char *str = "GfG"; /* Stored in read only part of shared segment */ /* No problem: remains at address str after getString() returns*/ return str; } int main(){ printf("%s", getString()); getchar(); return 0;} The below program also works perfectly fine as the string is stored in heap segment and data stored in heap segment persists even after the return of getString() C char *getString(){ int size = 4; char *str = (char *)malloc(sizeof(char)*size); /*Stored in heap segment*/ *(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\0'; /* No problem: string remains at str after getString() returns */ return str; } int main(){ printf("%s", getString()); getchar(); return 0;} But, the below program may print some garbage data as string is stored in stack frame of function getString() and data may not be there after getString() returns. C char *getString(){ char str[] = "GfG"; /* Stored in stack segment */ /* Problem: string may not be present after getString() returns */ /* Problem can be solved if write static before char, i.e. static char str[] = "GfG";*/ return str; } int main(){ printf("%s", getString()); getchar(); return 0;} Please write comments if you find anything incorrect in the above article, or you want to share more information about the storage of strings Akanksha_Rai gunturupruthvi27 kanchanchauhankc C Array and String Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity SQL Interview Questions Understanding "extern" keyword in C SQL | Views std::sort() in C++ STL Bitwise Operators in C/C++ Arrays in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jul, 2021" }, { "code": null, "e": 176, "s": 54, "text": "In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays " }, { "code": null, "e": 178, "s": 176, "text": "C" }, { "code": "char str[4] = \"GfG\"; /*One extra for string terminator*//* OR */char str[4] = {‘G’, ‘f’, ‘G’, '\\0'}; /* '\\0' is string terminator */", "e": 317, "s": 178, "text": null }, { "code": null, "e": 565, "s": 317, "text": "When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then string is stored in stack segment, if it’s a global or static variable then stored in data segment, etc." }, { "code": null, "e": 657, "s": 565, "text": "Strings using character pointers Using character pointer strings can be stored in two ways:" }, { "code": null, "e": 873, "s": 657, "text": "1) Read only string in a shared segment. When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read-only block (generally in data segment) that is shared among functions. " }, { "code": null, "e": 875, "s": 873, "text": "C" }, { "code": "char *str = \"GfG\"; ", "e": 898, "s": 875, "text": null }, { "code": null, "e": 1209, "s": 898, "text": "In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in the program." }, { "code": null, "e": 1252, "s": 1209, "text": "2) Dynamically allocated in heap segment. " }, { "code": null, "e": 1352, "s": 1252, "text": "Strings are stored like other dynamically allocated things in C and can be shared among functions. " }, { "code": null, "e": 1354, "s": 1352, "text": "C" }, { "code": "char *str;int size = 4; /*one extra for ‘\\0’*/str = (char *)malloc(sizeof(char)*size);*(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\\0'; ", "e": 1509, "s": 1354, "text": null }, { "code": null, "e": 1588, "s": 1509, "text": "Let us see some examples to better understand the above ways to store strings." }, { "code": null, "e": 1750, "s": 1588, "text": "Example 1 (Try to modify string) The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory. " }, { "code": null, "e": 1752, "s": 1750, "text": "C" }, { "code": "int main(){ char *str; str = \"GfG\"; /* Stored in read only part of data segment */ *(str+1) = 'n'; /* Problem: trying to modify read only memory */ getchar(); return 0;}", "e": 1928, "s": 1752, "text": null }, { "code": null, "e": 2014, "s": 1928, "text": "The below program works perfectly fine as str[] is stored in writable stack segment. " }, { "code": null, "e": 2016, "s": 2014, "text": "C" }, { "code": "int main(){ char str[] = \"GfG\"; /* Stored in stack segment like other auto variables */ *(str+1) = 'n'; /* No problem: String is now GnG */ getchar(); return 0;}", "e": 2181, "s": 2016, "text": null }, { "code": null, "e": 2273, "s": 2181, "text": "Below program also works perfectly fine as data at str is stored in writable heap segment. " }, { "code": null, "e": 2275, "s": 2273, "text": "C" }, { "code": "int main(){ int size = 4; /* Stored in heap segment like other dynamically allocated things */ char *str = (char *)malloc(sizeof(char)*size); *(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\\0'; *(str+1) = 'n'; /* No problem: String is now GnG */ getchar(); return 0;} ", "e": 2585, "s": 2275, "text": null }, { "code": null, "e": 2781, "s": 2585, "text": "Example 2 (Try to return string from a function) The below program works perfectly fine as the string is stored in a shared segment and data stored remains there even after return of getString() " }, { "code": null, "e": 2783, "s": 2781, "text": "C" }, { "code": "char *getString(){ char *str = \"GfG\"; /* Stored in read only part of shared segment */ /* No problem: remains at address str after getString() returns*/ return str; } int main(){ printf(\"%s\", getString()); getchar(); return 0;}", "e": 3028, "s": 2783, "text": null }, { "code": null, "e": 3192, "s": 3028, "text": "The below program also works perfectly fine as the string is stored in heap segment and data stored in heap segment persists even after the return of getString() " }, { "code": null, "e": 3194, "s": 3192, "text": "C" }, { "code": "char *getString(){ int size = 4; char *str = (char *)malloc(sizeof(char)*size); /*Stored in heap segment*/ *(str+0) = 'G'; *(str+1) = 'f'; *(str+2) = 'G'; *(str+3) = '\\0'; /* No problem: string remains at str after getString() returns */ return str; } int main(){ printf(\"%s\", getString()); getchar(); return 0;}", "e": 3538, "s": 3194, "text": null }, { "code": null, "e": 3702, "s": 3538, "text": "But, the below program may print some garbage data as string is stored in stack frame of function getString() and data may not be there after getString() returns. " }, { "code": null, "e": 3704, "s": 3702, "text": "C" }, { "code": "char *getString(){ char str[] = \"GfG\"; /* Stored in stack segment */ /* Problem: string may not be present after getString() returns */ /* Problem can be solved if write static before char, i.e. static char str[] = \"GfG\";*/ return str; } int main(){ printf(\"%s\", getString()); getchar(); return 0;}", "e": 4018, "s": 3704, "text": null }, { "code": null, "e": 4161, "s": 4018, "text": "Please write comments if you find anything incorrect in the above article, or you want to share more information about the storage of strings " }, { "code": null, "e": 4174, "s": 4161, "text": "Akanksha_Rai" }, { "code": null, "e": 4191, "s": 4174, "text": "gunturupruthvi27" }, { "code": null, "e": 4208, "s": 4191, "text": "kanchanchauhankc" }, { "code": null, "e": 4227, "s": 4208, "text": "C Array and String" }, { "code": null, "e": 4236, "s": 4227, "text": "Articles" }, { "code": null, "e": 4247, "s": 4236, "text": "C Language" }, { "code": null, "e": 4345, "s": 4247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4398, "s": 4345, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 4435, "s": 4398, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 4459, "s": 4435, "text": "SQL Interview Questions" }, { "code": null, "e": 4495, "s": 4459, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 4507, "s": 4495, "text": "SQL | Views" }, { "code": null, "e": 4530, "s": 4507, "text": "std::sort() in C++ STL" }, { "code": null, "e": 4557, "s": 4530, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4573, "s": 4557, "text": "Arrays in C/C++" }, { "code": null, "e": 4590, "s": 4573, "text": "Substring in C++" } ]
JUnit - Execution Procedure
This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example. Create a java class file named ExecutionProcedureJunit.java in C:\>JUNIT_WORKSPACE to test annotation. import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class ExecutionProcedureJunit { //execute only once, in the starting @BeforeClass public static void beforeClass() { System.out.println("in before class"); } //execute only once, in the end @AfterClass public static void afterClass() { System.out.println("in after class"); } //execute for each test, before executing test @Before public void before() { System.out.println("in before"); } //execute for each test, after executing test @After public void after() { System.out.println("in after"); } //test case 1 @Test public void testCase1() { System.out.println("in test case 1"); } //test case 2 @Test public void testCase2() { System.out.println("in test case 2"); } } Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute annotations. import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the Test case and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java Now run the Test Runner, which will run the test case defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. in before class in before in test case 1 in after in before in test case 2 in after in after class See the above output. The execution procedure is as follows − First of all, the beforeClass() method executes only once. The afterClass() method executes only once. The before() method executes for each test case, but before executing the test case. The after() method executes for each test case, but after the execution of test case. In between before() and after(), each test case executes. 24 Lectures 2.5 hours Nishita Bhatt 56 Lectures 7.5 hours Dinesh Varyani Print Add Notes Bookmark this page
[ { "code": null, "e": 2173, "s": 1972, "text": "This chapter explains the execution procedure of methods in JUnit, which defines the order of the methods called. Discussed below is the execution procedure of the JUnit test API methods with example." }, { "code": null, "e": 2276, "s": 2173, "text": "Create a java class file named ExecutionProcedureJunit.java in C:\\>JUNIT_WORKSPACE to test annotation." }, { "code": null, "e": 3233, "s": 2276, "text": "import org.junit.After;\nimport org.junit.AfterClass;\n\nimport org.junit.Before;\nimport org.junit.BeforeClass;\n\nimport org.junit.Ignore;\nimport org.junit.Test;\n\npublic class ExecutionProcedureJunit {\n\t\n //execute only once, in the starting \n @BeforeClass\n public static void beforeClass() {\n System.out.println(\"in before class\");\n }\n\n //execute only once, in the end\n @AfterClass\n public static void afterClass() {\n System.out.println(\"in after class\");\n }\n\n //execute for each test, before executing test\n @Before\n public void before() {\n System.out.println(\"in before\");\n }\n\t\n //execute for each test, after executing test\n @After\n public void after() {\n System.out.println(\"in after\");\n }\n\t\n //test case 1\n @Test\n public void testCase1() {\n System.out.println(\"in test case 1\");\n }\n\n //test case 2\n @Test\n public void testCase2() {\n System.out.println(\"in test case 2\");\n }\n}" }, { "code": null, "e": 3333, "s": 3233, "text": "Next, create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute annotations." }, { "code": null, "e": 3764, "s": 3333, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(ExecutionProcedureJunit.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} " }, { "code": null, "e": 3823, "s": 3764, "text": "Compile the Test case and Test Runner classes using javac." }, { "code": null, "e": 3894, "s": 3823, "text": "C:\\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java\n" }, { "code": null, "e": 3989, "s": 3894, "text": "Now run the Test Runner, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 4025, "s": 3989, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 4044, "s": 4025, "text": "Verify the output." }, { "code": null, "e": 4144, "s": 4044, "text": "in before class\nin before\nin test case 1\nin after\nin before\nin test case 2\nin after\nin after class\n" }, { "code": null, "e": 4206, "s": 4144, "text": "See the above output. The execution procedure is as follows −" }, { "code": null, "e": 4265, "s": 4206, "text": "First of all, the beforeClass() method executes only once." }, { "code": null, "e": 4309, "s": 4265, "text": "The afterClass() method executes only once." }, { "code": null, "e": 4394, "s": 4309, "text": "The before() method executes for each test case, but before executing the test case." }, { "code": null, "e": 4480, "s": 4394, "text": "The after() method executes for each test case, but after the execution of test case." }, { "code": null, "e": 4538, "s": 4480, "text": "In between before() and after(), each test case executes." }, { "code": null, "e": 4573, "s": 4538, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4588, "s": 4573, "text": " Nishita Bhatt" }, { "code": null, "e": 4623, "s": 4588, "text": "\n 56 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4639, "s": 4623, "text": " Dinesh Varyani" }, { "code": null, "e": 4646, "s": 4639, "text": " Print" }, { "code": null, "e": 4657, "s": 4646, "text": " Add Notes" } ]
Calculate the difference between Consecutive pair of Elements of a Vector in R Programming - diff() Function - GeeksforGeeks
05 Jun, 2020 diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector. Syntax: diff(x, lag, differences) Parameters:x: vector or matrixlag: period between elementsdifferences: Order of difference Example 1: # R program to find the difference# between each pair of elements of a vector # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10)x3 <- c(-1:-8) # Calling diff() functiondiff(x1)diff(x2)diff(x3) Output: [1] -6 3 -1 5 -3 48 -36 [1] 1 1 1 1 1 1 1 1 1 [1] -1 -1 -1 -1 -1 -1 -1 Example 2: # R program to find the difference# between each pair of elements of a vector # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10) # Calling diff() functiondiff(x1, lag = 2, differences = 1)diff(x2, lag = 1, differences = 2) Output: [1] -3 2 4 2 45 12 [1] 0 0 0 0 0 0 0 0 Here, in the above code, the ‘lag’ tells the period between values, i.e. lag = 2 means, diff is calculated between 1st and 3rd value, 2nd and 4th values, etc. and ‘differences’ tells the order in which diff() function is called i.e. differences = 2 means diff() function is called twice on the vector. R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24850, "s": 24822, "text": "\n05 Jun, 2020" }, { "code": null, "e": 24966, "s": 24850, "text": "diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector." }, { "code": null, "e": 25000, "s": 24966, "text": "Syntax: diff(x, lag, differences)" }, { "code": null, "e": 25091, "s": 25000, "text": "Parameters:x: vector or matrixlag: period between elementsdifferences: Order of difference" }, { "code": null, "e": 25102, "s": 25091, "text": "Example 1:" }, { "code": "# R program to find the difference# between each pair of elements of a vector # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10)x3 <- c(-1:-8) # Calling diff() functiondiff(x1)diff(x2)diff(x3)", "e": 25312, "s": 25102, "text": null }, { "code": null, "e": 25320, "s": 25312, "text": "Output:" }, { "code": null, "e": 25400, "s": 25320, "text": "[1] -6 3 -1 5 -3 48 -36\n[1] 1 1 1 1 1 1 1 1 1\n[1] -1 -1 -1 -1 -1 -1 -1\n" }, { "code": null, "e": 25411, "s": 25400, "text": "Example 2:" }, { "code": "# R program to find the difference# between each pair of elements of a vector # Creating a vectorx1 <- c(8, 2, 5, 4, 9, 6, 54, 18)x2 <- c(1:10) # Calling diff() functiondiff(x1, lag = 2, differences = 1)diff(x2, lag = 1, differences = 2)", "e": 25651, "s": 25411, "text": null }, { "code": null, "e": 25659, "s": 25651, "text": "Output:" }, { "code": null, "e": 25702, "s": 25659, "text": "[1] -3 2 4 2 45 12\n[1] 0 0 0 0 0 0 0 0\n" }, { "code": null, "e": 26004, "s": 25702, "text": "Here, in the above code, the ‘lag’ tells the period between values, i.e. lag = 2 means, diff is calculated between 1st and 3rd value, 2nd and 4th values, etc. and ‘differences’ tells the order in which diff() function is called i.e. differences = 2 means diff() function is called twice on the vector." }, { "code": null, "e": 26022, "s": 26004, "text": "R Vector-Function" }, { "code": null, "e": 26033, "s": 26022, "text": "R Language" }, { "code": null, "e": 26131, "s": 26033, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26189, "s": 26131, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26241, "s": 26189, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26273, "s": 26241, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26325, "s": 26273, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26369, "s": 26325, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26401, "s": 26369, "text": "Printing Output of an R Program" }, { "code": null, "e": 26439, "s": 26401, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26488, "s": 26439, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26523, "s": 26488, "text": "Group by function in R using Dplyr" } ]
QR code generating website in Django
We sometimes need to generate the QR code of an URL in our website. QR codes are scanned for verification, website login, opening websites and many things like that. In this article, we will see how to implement that. We are going to create a qrgenerator website in Django. Create a Django project and an app. Create a media folder at the same level of project and app. Go to settings.py in the project folder and add the app name in INSTALLED_APPS and add this at the bottom − MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' Here we set up our media folder where we will store our QR code. In urls.py of the project directory, add the following − from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path("",include("qrgenerator.urls")) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Here we defined the app urls and media folder url. qrgenerator is my app name. Now install two libraries: PIL an qrcode. pip install PIL pip install qrcode In app's urls.py − from django.urls import path,include from . import views urlpatterns = [ path('', views.home,name='Home'), ] Here we rendered our home view on main url. In view.py, add the following lines − from django.shortcuts import render from .models import QrCode # Create your views here. def home(request): if request.method=="POST": Url=request.POST['url'] QrCode.objects.create(url=Url) qr_code=QrCode.objects.all() return render(request,"home.html",{'qr_code':qr_code}) Here we took the url and then created a qrcode model's object and in the GET handler, we returned all our QR codes. Create a "templates" folder in app directory (at the same level of migration folder) and add a file "home.html" in it with the following lines − <!DOCTYPE html> <html> <head> <title>tut</title> </head> <body> <form method="POST"> {% csrf_token %} <input type="url" placeholder="URL PLEASE" requir ed name="url"> <button type= "submit" >get qrcode</button> </form> {% for qr in qr_code %} <img src="{{qr.image.url}}"/><br> {%endfor%} </body> </html> Here we created an input box to take the url and send it to the backend. Below <form>, we loop through each QR code object and show them as images. Go to models.py and add the following lines − from django.db import models import qrcode from PIL import Image, ImageDraw from io import BytesIO from django.core.files import File # Create your models here. import random class QrCode(models.Model): url=models.URLField() image=models.ImageField(upload_to='qrcode',blank=True) def save(self,*args,**kwargs): qrcode_img=qrcode.make(self.url) canvas=Image.new("RGB", (300,300),"white") draw=ImageDraw.Draw(canvas) canvas.paste(qrcode_img) buffer=BytesIO() canvas.save(buffer,"PNG") self.image.save(f'image{random.randint(0,9999)}',File(buffer),save=False) canvas.close() super().save(*args,**kwargs) Here we defined our own save method, which takes arguments. We used the qrcode library to generate the QR code and then we used the canvas to make it black and white. Then we added that QR code over the canvas and saved that as an image. We saved the image in the media folder and add it as a model instance. Now, everything is set and you can proceed to check the output.
[ { "code": null, "e": 1336, "s": 1062, "text": "We sometimes need to generate the QR code of an URL in our website. QR codes are scanned for verification, website login, opening websites and many things like that. In this article, we will see how to implement that. We are going to create a qrgenerator website in Django." }, { "code": null, "e": 1432, "s": 1336, "text": "Create a Django project and an app. Create a media folder at the same level of project and app." }, { "code": null, "e": 1540, "s": 1432, "text": "Go to settings.py in the project folder and add the app name in INSTALLED_APPS and add this at the bottom −" }, { "code": null, "e": 1608, "s": 1540, "text": "MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\nMEDIA_URL = '/media/'" }, { "code": null, "e": 1673, "s": 1608, "text": "Here we set up our media folder where we will store our QR code." }, { "code": null, "e": 1730, "s": 1673, "text": "In urls.py of the project directory, add the following −" }, { "code": null, "e": 2047, "s": 1730, "text": "from django.contrib import admin\nfrom django.urls import path,include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path(\"\",include(\"qrgenerator.urls\"))\n]\nurlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)" }, { "code": null, "e": 2126, "s": 2047, "text": "Here we defined the app urls and media folder url. qrgenerator is my app name." }, { "code": null, "e": 2168, "s": 2126, "text": "Now install two libraries: PIL an qrcode." }, { "code": null, "e": 2203, "s": 2168, "text": "pip install PIL\npip install qrcode" }, { "code": null, "e": 2222, "s": 2203, "text": "In app's urls.py −" }, { "code": null, "e": 2335, "s": 2222, "text": "from django.urls import path,include\nfrom . import views\n\nurlpatterns = [\n path('', views.home,name='Home'),\n]" }, { "code": null, "e": 2379, "s": 2335, "text": "Here we rendered our home view on main url." }, { "code": null, "e": 2417, "s": 2379, "text": "In view.py, add the following lines −" }, { "code": null, "e": 2713, "s": 2417, "text": "from django.shortcuts import render\nfrom .models import QrCode\n# Create your views here.\ndef home(request):\n if request.method==\"POST\":\n Url=request.POST['url']\n QrCode.objects.create(url=Url)\n\n qr_code=QrCode.objects.all()\n return render(request,\"home.html\",{'qr_code':qr_code})" }, { "code": null, "e": 2829, "s": 2713, "text": "Here we took the url and then created a qrcode model's object and in the GET handler, we returned all our QR codes." }, { "code": null, "e": 2974, "s": 2829, "text": "Create a \"templates\" folder in app directory (at the same level of migration folder) and add a file \"home.html\" in it with the following lines −" }, { "code": null, "e": 3353, "s": 2974, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>tut</title>\n </head>\n <body>\n <form method=\"POST\">\n {% csrf_token %}\n <input type=\"url\" placeholder=\"URL PLEASE\" requir\ned name=\"url\">\n <button type= \"submit\" >get qrcode</button>\n </form>\n {% for qr in qr_code %}\n <img src=\"{{qr.image.url}}\"/><br>\n {%endfor%}\n </body>\n</html>" }, { "code": null, "e": 3501, "s": 3353, "text": "Here we created an input box to take the url and send it to the backend. Below <form>, we loop through each QR code object and show them as images." }, { "code": null, "e": 3547, "s": 3501, "text": "Go to models.py and add the following lines −" }, { "code": null, "e": 4213, "s": 3547, "text": "from django.db import models\nimport qrcode\nfrom PIL import Image, ImageDraw\nfrom io import BytesIO\nfrom django.core.files import File\n\n# Create your models here.\nimport random\nclass QrCode(models.Model):\n url=models.URLField()\n image=models.ImageField(upload_to='qrcode',blank=True)\n\n def save(self,*args,**kwargs):\n qrcode_img=qrcode.make(self.url)\n canvas=Image.new(\"RGB\", (300,300),\"white\")\n draw=ImageDraw.Draw(canvas)\n canvas.paste(qrcode_img)\n buffer=BytesIO()\n canvas.save(buffer,\"PNG\")\n self.image.save(f'image{random.randint(0,9999)}',File(buffer),save=False)\n canvas.close()\n super().save(*args,**kwargs)" }, { "code": null, "e": 4522, "s": 4213, "text": "Here we defined our own save method, which takes arguments. We used the qrcode library to generate the QR code and then we used the canvas to make it black and white. Then we added that QR code over the canvas and saved that as an image. We saved the image in the media folder and add it as a model instance." }, { "code": null, "e": 4586, "s": 4522, "text": "Now, everything is set and you can proceed to check the output." } ]
Rexx - Functions
The code in Rexx is normally divided into Functions and Subroutines. Using functions helps in segregating the code into many more logical units. Let’s look at these functions in detail. The syntax of a function declaration is as follows − FunctionName: PARSE ARG arguement1, arguement2... arguementN Return value Where, FunctionName − This is the name assigned to the function. FunctionName − This is the name assigned to the function. PARSE ARG − These are keywords in Rexx which are used to mention that parameters are being passed onto the function. PARSE ARG − These are keywords in Rexx which are used to mention that parameters are being passed onto the function. arguement1, arguement2... arguementN − These are the arguments passed to the function. arguement1, arguement2... arguementN − These are the arguments passed to the function. Return value − This is the value returned by the function. Return value − This is the value returned by the function. The following program is a simple example of how functions are used in Rexx. /* Main program */ say add(5,6) exit add: PARSE ARG a,b return a + b The following things should be noted about the above program − We are defining a function called add which accepts 2 parameters a and b. We are defining a function called add which accepts 2 parameters a and b. The function uses the return statement to return the sum of a and b. The function uses the return statement to return the sum of a and b. The exit statement has to be used to signify the end of the main program. The exit statement has to be used to signify the end of the main program. The output of the above program would be as follows − 11 In Rexx, there are specific functions which can be made to work with arguments. Let’s look at a couple of such arguments. This method is used to return the number of arguments defined for the function. Syntax − arg() Parameters − None Return Value − This method returns the number of arguments defined for the function. Example − /* Main program */ say add(5,6) exit add: PARSE ARG a,b say arg() return a + b Output − When we run the above program we will get the following result. 2 11 This method is used to return the value of the argument at the specific position. Syntax − arg(index) Parameter − Index − Index position of the argument to be returned. Index − Index position of the argument to be returned. Return Value − This method returns the value of the argument at the specific position. Example − /* Main program */ say add(5,6) exit add: PARSE ARG a,b say arg(1) return a + b Output − When we run the above program we will get the following result. 5 11 A recursive function or routine is one that calls itself. Any recursive function could be coded in a traditional non-recursive fashion (or iteratively), but sometimes recursion offers a better problem solution. Not all programming languages support recursion; Rexx does. Let’s see an example of the famous factorial program using recursive functions in Rexx. /* Main program */ do n = 1 to 5 say 'The factorial of' n 'is:' factorial( n ) end return /* Function to get factorial */ factorial : procedure n = arg(1) if n = 1 then return 1 return n * factorial( n - 1 ) The output of the above program is as follows − The factorial of 1 is: 1 The factorial of 2 is: 2 The factorial of 3 is: 6 The factorial of 3 is: 24 The factorial of 3 is: 120 Print Add Notes Bookmark this page
[ { "code": null, "e": 2525, "s": 2339, "text": "The code in Rexx is normally divided into Functions and Subroutines. Using functions helps in segregating the code into many more logical units. Let’s look at these functions in detail." }, { "code": null, "e": 2578, "s": 2525, "text": "The syntax of a function declaration is as follows −" }, { "code": null, "e": 2656, "s": 2578, "text": "FunctionName: \nPARSE ARG arguement1, arguement2... arguementN \nReturn value \n" }, { "code": null, "e": 2663, "s": 2656, "text": "Where," }, { "code": null, "e": 2721, "s": 2663, "text": "FunctionName − This is the name assigned to the function." }, { "code": null, "e": 2779, "s": 2721, "text": "FunctionName − This is the name assigned to the function." }, { "code": null, "e": 2896, "s": 2779, "text": "PARSE ARG − These are keywords in Rexx which are used to mention that parameters are being passed onto the function." }, { "code": null, "e": 3013, "s": 2896, "text": "PARSE ARG − These are keywords in Rexx which are used to mention that parameters are being passed onto the function." }, { "code": null, "e": 3100, "s": 3013, "text": "arguement1, arguement2... arguementN − These are the arguments passed to the function." }, { "code": null, "e": 3187, "s": 3100, "text": "arguement1, arguement2... arguementN − These are the arguments passed to the function." }, { "code": null, "e": 3246, "s": 3187, "text": "Return value − This is the value returned by the function." }, { "code": null, "e": 3305, "s": 3246, "text": "Return value − This is the value returned by the function." }, { "code": null, "e": 3382, "s": 3305, "text": "The following program is a simple example of how functions are used in Rexx." }, { "code": null, "e": 3457, "s": 3382, "text": "/* Main program */ \nsay add(5,6) \nexit \nadd: \nPARSE ARG a,b \nreturn a + b " }, { "code": null, "e": 3520, "s": 3457, "text": "The following things should be noted about the above program −" }, { "code": null, "e": 3594, "s": 3520, "text": "We are defining a function called add which accepts 2 parameters a and b." }, { "code": null, "e": 3668, "s": 3594, "text": "We are defining a function called add which accepts 2 parameters a and b." }, { "code": null, "e": 3737, "s": 3668, "text": "The function uses the return statement to return the sum of a and b." }, { "code": null, "e": 3806, "s": 3737, "text": "The function uses the return statement to return the sum of a and b." }, { "code": null, "e": 3880, "s": 3806, "text": "The exit statement has to be used to signify the end of the main program." }, { "code": null, "e": 3954, "s": 3880, "text": "The exit statement has to be used to signify the end of the main program." }, { "code": null, "e": 4008, "s": 3954, "text": "The output of the above program would be as follows −" }, { "code": null, "e": 4012, "s": 4008, "text": "11\n" }, { "code": null, "e": 4134, "s": 4012, "text": "In Rexx, there are specific functions which can be made to work with arguments. Let’s look at a couple of such arguments." }, { "code": null, "e": 4214, "s": 4134, "text": "This method is used to return the number of arguments defined for the function." }, { "code": null, "e": 4223, "s": 4214, "text": "Syntax −" }, { "code": null, "e": 4231, "s": 4223, "text": "arg() \n" }, { "code": null, "e": 4249, "s": 4231, "text": "Parameters − None" }, { "code": null, "e": 4334, "s": 4249, "text": "Return Value − This method returns the number of arguments defined for the function." }, { "code": null, "e": 4344, "s": 4334, "text": "Example −" }, { "code": null, "e": 4431, "s": 4344, "text": "/* Main program */ \nsay add(5,6) \nexit \nadd: \nPARSE ARG a,b \n\nsay arg() \nreturn a + b " }, { "code": null, "e": 4504, "s": 4431, "text": "Output − When we run the above program we will get the following result." }, { "code": null, "e": 4512, "s": 4504, "text": "2 \n11 \n" }, { "code": null, "e": 4594, "s": 4512, "text": "This method is used to return the value of the argument at the specific position." }, { "code": null, "e": 4603, "s": 4594, "text": "Syntax −" }, { "code": null, "e": 4615, "s": 4603, "text": "arg(index)\n" }, { "code": null, "e": 4627, "s": 4615, "text": "Parameter −" }, { "code": null, "e": 4682, "s": 4627, "text": "Index − Index position of the argument to be returned." }, { "code": null, "e": 4737, "s": 4682, "text": "Index − Index position of the argument to be returned." }, { "code": null, "e": 4824, "s": 4737, "text": "Return Value − This method returns the value of the argument at the specific position." }, { "code": null, "e": 4834, "s": 4824, "text": "Example −" }, { "code": null, "e": 4922, "s": 4834, "text": "/* Main program */ \nsay add(5,6) \nexit \nadd: \nPARSE ARG a,b \n\nsay arg(1) \nreturn a + b " }, { "code": null, "e": 4995, "s": 4922, "text": "Output − When we run the above program we will get the following result." }, { "code": null, "e": 5003, "s": 4995, "text": "5 \n11 \n" }, { "code": null, "e": 5274, "s": 5003, "text": "A recursive function or routine is one that calls itself. Any recursive function could be coded in a traditional non-recursive fashion (or iteratively), but sometimes recursion offers a better problem solution. Not all programming languages support recursion; Rexx does." }, { "code": null, "e": 5362, "s": 5274, "text": "Let’s see an example of the famous factorial program using recursive functions in Rexx." }, { "code": null, "e": 5583, "s": 5362, "text": "/* Main program */ \ndo n = 1 to 5 \nsay 'The factorial of' n 'is:' factorial( n ) \nend \nreturn \n\n/* Function to get factorial */ \nfactorial : procedure \nn = arg(1) \nif n = 1 then \nreturn 1 \nreturn n * factorial( n - 1 ) " }, { "code": null, "e": 5631, "s": 5583, "text": "The output of the above program is as follows −" }, { "code": null, "e": 5764, "s": 5631, "text": "The factorial of 1 is: 1\nThe factorial of 2 is: 2 \nThe factorial of 3 is: 6 \nThe factorial of 3 is: 24 \nThe factorial of 3 is: 120 \n" }, { "code": null, "e": 5771, "s": 5764, "text": " Print" }, { "code": null, "e": 5782, "s": 5771, "text": " Add Notes" } ]
QlikView - Synthetic Key
A Synthetic Key is QlikView's solution to create an artificial key when there is ambiguity about which key to use between two tables. This situation arises when two tables have two or more fields in common. QlikView's feature of creating association in memory automatically detects this scenario and creates an additional table, which will hold the value of the new key created. Let us consider the following two CSV data files, which are used as input for further illustrations. Sales: ProductID,ProductCategory,Country,SaleAmount 1,Outdoor Recreation,Italy,4579 2,Clothing,USA,4125 3,Costumes & Accessories,South Korea,6521 Product: ProductID, Country 3,Brazil 3,China 2,Korea 1,USA We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Next, we look at the data model by using the menu command for table viewer, Control+T. The following screen comes up, which shows the creation of a third table that supplies the value of the synthetic key as both the tables have ProductID and Country as matching keys. Synthetic keys indicate the flaw in the data model that is being used. They do not cause any issue in the correctness of the data or performance of the report. Things will work fine if a big data model has one or two instances of synthetic keys. However, if we have too many of them, then that is an implication to redesign the data model. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3299, "s": 2920, "text": "A Synthetic Key is QlikView's solution to create an artificial key when there is ambiguity about which key to use between two tables. This situation arises when two tables have two or more fields in common. QlikView's feature of creating association in memory\nautomatically detects this scenario and creates an additional table, which will hold the value of the new key created." }, { "code": null, "e": 3400, "s": 3299, "text": "Let us consider the following two CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 3607, "s": 3400, "text": "Sales:\nProductID,ProductCategory,Country,SaleAmount\n1,Outdoor Recreation,Italy,4579\n2,Clothing,USA,4125\n3,Costumes & Accessories,South Korea,6521\n\nProduct:\nProductID, Country\n3,Brazil\n3,China\n2,Korea\n1,USA\n" }, { "code": null, "e": 3762, "s": 3607, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file." }, { "code": null, "e": 4031, "s": 3762, "text": "Next, we look at the data model by using the menu command for table viewer, Control+T. The following screen comes up, which shows the creation of a third table that supplies the value of the synthetic key as both the tables have ProductID and Country as matching keys." }, { "code": null, "e": 4371, "s": 4031, "text": "Synthetic keys indicate the flaw in the data model that is being used. They do not cause any issue in the correctness of the data or performance of the report. Things will work fine if a big data model has one or two instances of synthetic keys. However, if we have too many of them, then that is an implication to redesign the data model." }, { "code": null, "e": 4404, "s": 4371, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 4417, "s": 4404, "text": " Arthur Fong" }, { "code": null, "e": 4424, "s": 4417, "text": " Print" }, { "code": null, "e": 4435, "s": 4424, "text": " Add Notes" } ]
How to Find the Right Architecture for Neural Network and Fine Tune Hyperparameters | by Asutosh Nayak | Towards Data Science
This blog post is a continuation of my previous post on how to use LSTMs to predict stock price for a stock, given its historical data. We have seen how to compile a Keras LSTM model. Here we will see some of the ways in which we can find the right architecture and hyperparameters. Here are some of our options: Hand Tuning or Manual search — This the the most painful method of finding right configuration wherein you try specific values for each parameters one by one. But with some experience, careful analysis of initial results and gut feeling it may prove really helpful.Grid Search — This is really the only way which can give you the best set of parameters out of all the options fed to it. You pass on a range of values for each parameter that you want to optimize, then train and find validation loss for each combination. As you can imagine this the most time consuming method and often not feasible.Random Search — This a subset of Grid Search which randomly selects subset of all possible combinations.Bayesian Optimization/Other probabilistic optimizations — This (Bayesian Optimization) method is really mathematically involved and to be honest I haven’t explored the maths in it. I will just give an overview of what it really does, even if you don’t know the internal workings you can still apply it in program like we will see later. Bayesian Optimization uses something called Gaussian Process to guess or model the objective function (the function we want to minimize by finding right set of hyperparameters). In this method a limit is set on how many times do we want to evaluate our objective function since it’s assumed to be very expensive. First a random set of points are decided within the range of parameters to observe the values of the function. Then using those results Gaussian process is used to guess the objective function. Post which an “acquisition function” is used to decide which point to sample next. And this process is repeated for “limit” number of times which is set above. You can refer this and this for in depth knowledge. There are other techniques too like TPE which is implemented using Hyperopt (code below). You can check this paper to understand TPE. Hand Tuning or Manual search — This the the most painful method of finding right configuration wherein you try specific values for each parameters one by one. But with some experience, careful analysis of initial results and gut feeling it may prove really helpful. Grid Search — This is really the only way which can give you the best set of parameters out of all the options fed to it. You pass on a range of values for each parameter that you want to optimize, then train and find validation loss for each combination. As you can imagine this the most time consuming method and often not feasible. Random Search — This a subset of Grid Search which randomly selects subset of all possible combinations. Bayesian Optimization/Other probabilistic optimizations — This (Bayesian Optimization) method is really mathematically involved and to be honest I haven’t explored the maths in it. I will just give an overview of what it really does, even if you don’t know the internal workings you can still apply it in program like we will see later. Bayesian Optimization uses something called Gaussian Process to guess or model the objective function (the function we want to minimize by finding right set of hyperparameters). In this method a limit is set on how many times do we want to evaluate our objective function since it’s assumed to be very expensive. First a random set of points are decided within the range of parameters to observe the values of the function. Then using those results Gaussian process is used to guess the objective function. Post which an “acquisition function” is used to decide which point to sample next. And this process is repeated for “limit” number of times which is set above. You can refer this and this for in depth knowledge. There are other techniques too like TPE which is implemented using Hyperopt (code below). You can check this paper to understand TPE. If you are using SK-Learn models then you can utilise their GridSearchCV directly. It is fairly straight forward to use. You can visit the link to their documentation above. An advantage is that it has option to run jobs in parallel too. If you are using Keras model then you will have to use the wrappers for Keras model as explained here. But if it doesn’t work or you don’t want the overhead of learning the syntax for a new package you can implement a bare minimum grid search like this : Other Smarter Search Implementation There are several open source packages available for minimizing objective functions using other “smarter” search algorithms. I will be showing examples for HyperOpt and Talos. Below is how you would implement hyperparameter tuning using Hyperopt which uses TPE algorithm to minimize function. In the above code snippet variable “search_space” holds the parameters and their values that you want to search. “fmin” function at the end is the actual function that does minimization. The program itself is pretty simple and I have added comments to it so it shouldn’t be a problem to understand. But I would like to dig deeper into formation of search space dictionary because that’s slightly awkward. Let’s put it under microscope : The main dictionary holds all the keys for the parameters that we want to optimize. We would mostly deal with two functions (or stochastic expressions, as they call it) namely — choice and uniform. “hp.choice” takes in a list of values to try from. This function then returns one of the options, which should be a list or tuple. The string (first parameter) we pass to hp.choice and hp.uniform is used by Hyperopt for internal purposes mostly. “hp.uniform” returns a value uniformly between the 2nd and 3rd parameters passed (low and high). Where it gets tricky is, when you have parameter like “lstm_layers”, which defines the number of LSTM layers in the network. For such parameters we have two new sets of parameters to test : first when number of LSTM layers in the network is one, second when two LSTMs layers are used. In this case you can see that I have used hp.choice to tell the system my choices for this parameter (lstm_layers) and the value for this parameter is given by the key “layers”. When Hyperopt is testing the model with two LSTM layers it will consider 2 other parameters to test namely — number of nodes in 2nd LSTM layer (lstm2_nodes) and drop out to be used for 2nd LSTM layer (lstm2_dropouts). I have kept first lstm layer blank but you can include other parameters to test too. I hope I was clear with how to build sample space for practical purposes. Now let’s look into another library that claims to be using probabilistic methods (in combination with grid or random) to reduce the number of evaluations — Talos. The usage of Talos is similar to previous tool; you have to create a function that builds model, trains it, evaluates it on a validation data. Only difference is that model function returns Keras history object and model instead of a dictionary. Another thing to note here is that we pass X and Y here in Scan function but they are never used since we want to build data based on selected “batch_size” and “time_steps” in current iteration. But for simpler problems it would be easier. You could also use Hyperas (Hyperopt + Keras), which is a wrapper around Hyperopt. Main advantage is you don’t need to learn any new syntax/functions of Hyperopt. All you have to do is define a search space dictionary like before and build your model like shown below. All you have to do is place the values you want to test for a parameter within double curly braces ( e.g. {{ [1, 2, 3] }} ). But Hyperas didn’t work in this case, since I was calling ‘data’ function from ‘model’ function and the syntax of using double curly braces caused some problem. I didn’t dig into the issue as I already had other tools. Nevertheless I think its worth mentioning here, as it’s lot easier. This is all fine but how to know that the result returned by any of these tools is the best? If you ask me, we won’t know. You have to weigh the trade-off — how much time you have to spend on fine tuning versus how much validation loss is good enough for you to go ahead. In my opinion it would be best if you tried to spend some time doing hand tuning on the result of above tools. For instance when I was working on the stocks dataset I first wrote my own implementation of grid search and ran it on cloud. Then, I tried these above tools for smart tuning but unfortunately the cloud VM was quite slow (slower than my laptop!) that day and I was running out of patience. Fortunately, by the time I read about these tools, implemented and started running them on cloud, my grid search was done. I had ran grid search on these values : search_params = { "batch_size": [20, 30, 40], "time_steps": [30, 60, 90], "lr": [0.01, 0.001, 0.0001], "epochs": [30, 50, 70]} This search with only 4 parameters (81 combinations) ran for 24 hours! I don’t have the result to share here because I forgot to implement logging in excitement (mistake 1). By using the results from grid search, I got disappointing prediction : But I had not optimized other things like number of layers etc ( I had started with a Neural Net having 2 LSTM layers and 1 dense layer — mistake 2. Always start with simpler model, test the waters and then build your way up). Anyway, I decided to optimize further manually. I took the best result from grid search and tried other parameters. No matter how hard I tried I couldn’t improve the loss much. I knew it’s overfitting so I tried increasing the dropouts but to no avail. Then I had an epiphany that may be I am trying too hard and 1 LSTM layer is enough (yeah, I know I’m stupid — mistake 3 underestimating the power of neural networks). But how do you know if model is overfitting? It’s actually quite simple. In my case the training error vs validation error looked like this: First, when you see a big gap between loss on training data and validation data it’s overfitting. Logic behind this is that your model is learning very well from your training data but it’s unable to generalize it to the validation data (new data). Second thing is the uncanny shape of validation error plot. It’s all over the place. This means the model is just predicting random values on new data that’s why there’s almost no relation between validation losses across the epochs. Another thing to look for is the epoch logs. If you see that training loss keeps on decreasing but validation loss fluctuates or remains same after some time it’s probably overfitting. So I removed second layer of LSTM and added dropout layer with value higher than what I had been using (0.5 from 0.2). And voila! Drastic improvement right? I am pretty sure that with more effort we can make it even better. I am not sharing code snippet for training the model as it’s same as shown in above snippets; only with right parameters. You can find all the complete programs on my Github profile here. In the next article I will be sharing some important tools/tips that helped me a lot during this project and are usually not given enough diligence.
[ { "code": null, "e": 455, "s": 172, "text": "This blog post is a continuation of my previous post on how to use LSTMs to predict stock price for a stock, given its historical data. We have seen how to compile a Keras LSTM model. Here we will see some of the ways in which we can find the right architecture and hyperparameters." }, { "code": null, "e": 485, "s": 455, "text": "Here are some of our options:" }, { "code": null, "e": 2378, "s": 485, "text": "Hand Tuning or Manual search — This the the most painful method of finding right configuration wherein you try specific values for each parameters one by one. But with some experience, careful analysis of initial results and gut feeling it may prove really helpful.Grid Search — This is really the only way which can give you the best set of parameters out of all the options fed to it. You pass on a range of values for each parameter that you want to optimize, then train and find validation loss for each combination. As you can imagine this the most time consuming method and often not feasible.Random Search — This a subset of Grid Search which randomly selects subset of all possible combinations.Bayesian Optimization/Other probabilistic optimizations — This (Bayesian Optimization) method is really mathematically involved and to be honest I haven’t explored the maths in it. I will just give an overview of what it really does, even if you don’t know the internal workings you can still apply it in program like we will see later. Bayesian Optimization uses something called Gaussian Process to guess or model the objective function (the function we want to minimize by finding right set of hyperparameters). In this method a limit is set on how many times do we want to evaluate our objective function since it’s assumed to be very expensive. First a random set of points are decided within the range of parameters to observe the values of the function. Then using those results Gaussian process is used to guess the objective function. Post which an “acquisition function” is used to decide which point to sample next. And this process is repeated for “limit” number of times which is set above. You can refer this and this for in depth knowledge. There are other techniques too like TPE which is implemented using Hyperopt (code below). You can check this paper to understand TPE." }, { "code": null, "e": 2644, "s": 2378, "text": "Hand Tuning or Manual search — This the the most painful method of finding right configuration wherein you try specific values for each parameters one by one. But with some experience, careful analysis of initial results and gut feeling it may prove really helpful." }, { "code": null, "e": 2979, "s": 2644, "text": "Grid Search — This is really the only way which can give you the best set of parameters out of all the options fed to it. You pass on a range of values for each parameter that you want to optimize, then train and find validation loss for each combination. As you can imagine this the most time consuming method and often not feasible." }, { "code": null, "e": 3084, "s": 2979, "text": "Random Search — This a subset of Grid Search which randomly selects subset of all possible combinations." }, { "code": null, "e": 4274, "s": 3084, "text": "Bayesian Optimization/Other probabilistic optimizations — This (Bayesian Optimization) method is really mathematically involved and to be honest I haven’t explored the maths in it. I will just give an overview of what it really does, even if you don’t know the internal workings you can still apply it in program like we will see later. Bayesian Optimization uses something called Gaussian Process to guess or model the objective function (the function we want to minimize by finding right set of hyperparameters). In this method a limit is set on how many times do we want to evaluate our objective function since it’s assumed to be very expensive. First a random set of points are decided within the range of parameters to observe the values of the function. Then using those results Gaussian process is used to guess the objective function. Post which an “acquisition function” is used to decide which point to sample next. And this process is repeated for “limit” number of times which is set above. You can refer this and this for in depth knowledge. There are other techniques too like TPE which is implemented using Hyperopt (code below). You can check this paper to understand TPE." }, { "code": null, "e": 4615, "s": 4274, "text": "If you are using SK-Learn models then you can utilise their GridSearchCV directly. It is fairly straight forward to use. You can visit the link to their documentation above. An advantage is that it has option to run jobs in parallel too. If you are using Keras model then you will have to use the wrappers for Keras model as explained here." }, { "code": null, "e": 4767, "s": 4615, "text": "But if it doesn’t work or you don’t want the overhead of learning the syntax for a new package you can implement a bare minimum grid search like this :" }, { "code": null, "e": 4803, "s": 4767, "text": "Other Smarter Search Implementation" }, { "code": null, "e": 5096, "s": 4803, "text": "There are several open source packages available for minimizing objective functions using other “smarter” search algorithms. I will be showing examples for HyperOpt and Talos. Below is how you would implement hyperparameter tuning using Hyperopt which uses TPE algorithm to minimize function." }, { "code": null, "e": 5533, "s": 5096, "text": "In the above code snippet variable “search_space” holds the parameters and their values that you want to search. “fmin” function at the end is the actual function that does minimization. The program itself is pretty simple and I have added comments to it so it shouldn’t be a problem to understand. But I would like to dig deeper into formation of search space dictionary because that’s slightly awkward. Let’s put it under microscope :" }, { "code": null, "e": 6840, "s": 5533, "text": "The main dictionary holds all the keys for the parameters that we want to optimize. We would mostly deal with two functions (or stochastic expressions, as they call it) namely — choice and uniform. “hp.choice” takes in a list of values to try from. This function then returns one of the options, which should be a list or tuple. The string (first parameter) we pass to hp.choice and hp.uniform is used by Hyperopt for internal purposes mostly. “hp.uniform” returns a value uniformly between the 2nd and 3rd parameters passed (low and high). Where it gets tricky is, when you have parameter like “lstm_layers”, which defines the number of LSTM layers in the network. For such parameters we have two new sets of parameters to test : first when number of LSTM layers in the network is one, second when two LSTMs layers are used. In this case you can see that I have used hp.choice to tell the system my choices for this parameter (lstm_layers) and the value for this parameter is given by the key “layers”. When Hyperopt is testing the model with two LSTM layers it will consider 2 other parameters to test namely — number of nodes in 2nd LSTM layer (lstm2_nodes) and drop out to be used for 2nd LSTM layer (lstm2_dropouts). I have kept first lstm layer blank but you can include other parameters to test too." }, { "code": null, "e": 7078, "s": 6840, "text": "I hope I was clear with how to build sample space for practical purposes. Now let’s look into another library that claims to be using probabilistic methods (in combination with grid or random) to reduce the number of evaluations — Talos." }, { "code": null, "e": 7564, "s": 7078, "text": "The usage of Talos is similar to previous tool; you have to create a function that builds model, trains it, evaluates it on a validation data. Only difference is that model function returns Keras history object and model instead of a dictionary. Another thing to note here is that we pass X and Y here in Scan function but they are never used since we want to build data based on selected “batch_size” and “time_steps” in current iteration. But for simpler problems it would be easier." }, { "code": null, "e": 7958, "s": 7564, "text": "You could also use Hyperas (Hyperopt + Keras), which is a wrapper around Hyperopt. Main advantage is you don’t need to learn any new syntax/functions of Hyperopt. All you have to do is define a search space dictionary like before and build your model like shown below. All you have to do is place the values you want to test for a parameter within double curly braces ( e.g. {{ [1, 2, 3] }} )." }, { "code": null, "e": 8245, "s": 7958, "text": "But Hyperas didn’t work in this case, since I was calling ‘data’ function from ‘model’ function and the syntax of using double curly braces caused some problem. I didn’t dig into the issue as I already had other tools. Nevertheless I think its worth mentioning here, as it’s lot easier." }, { "code": null, "e": 8628, "s": 8245, "text": "This is all fine but how to know that the result returned by any of these tools is the best? If you ask me, we won’t know. You have to weigh the trade-off — how much time you have to spend on fine tuning versus how much validation loss is good enough for you to go ahead. In my opinion it would be best if you tried to spend some time doing hand tuning on the result of above tools." }, { "code": null, "e": 9081, "s": 8628, "text": "For instance when I was working on the stocks dataset I first wrote my own implementation of grid search and ran it on cloud. Then, I tried these above tools for smart tuning but unfortunately the cloud VM was quite slow (slower than my laptop!) that day and I was running out of patience. Fortunately, by the time I read about these tools, implemented and started running them on cloud, my grid search was done. I had ran grid search on these values :" }, { "code": null, "e": 9220, "s": 9081, "text": "search_params = { \"batch_size\": [20, 30, 40], \"time_steps\": [30, 60, 90], \"lr\": [0.01, 0.001, 0.0001], \"epochs\": [30, 50, 70]}" }, { "code": null, "e": 9466, "s": 9220, "text": "This search with only 4 parameters (81 combinations) ran for 24 hours! I don’t have the result to share here because I forgot to implement logging in excitement (mistake 1). By using the results from grid search, I got disappointing prediction :" }, { "code": null, "e": 10254, "s": 9466, "text": "But I had not optimized other things like number of layers etc ( I had started with a Neural Net having 2 LSTM layers and 1 dense layer — mistake 2. Always start with simpler model, test the waters and then build your way up). Anyway, I decided to optimize further manually. I took the best result from grid search and tried other parameters. No matter how hard I tried I couldn’t improve the loss much. I knew it’s overfitting so I tried increasing the dropouts but to no avail. Then I had an epiphany that may be I am trying too hard and 1 LSTM layer is enough (yeah, I know I’m stupid — mistake 3 underestimating the power of neural networks). But how do you know if model is overfitting? It’s actually quite simple. In my case the training error vs validation error looked like this:" }, { "code": null, "e": 10922, "s": 10254, "text": "First, when you see a big gap between loss on training data and validation data it’s overfitting. Logic behind this is that your model is learning very well from your training data but it’s unable to generalize it to the validation data (new data). Second thing is the uncanny shape of validation error plot. It’s all over the place. This means the model is just predicting random values on new data that’s why there’s almost no relation between validation losses across the epochs. Another thing to look for is the epoch logs. If you see that training loss keeps on decreasing but validation loss fluctuates or remains same after some time it’s probably overfitting." }, { "code": null, "e": 11052, "s": 10922, "text": "So I removed second layer of LSTM and added dropout layer with value higher than what I had been using (0.5 from 0.2). And voila!" }, { "code": null, "e": 11146, "s": 11052, "text": "Drastic improvement right? I am pretty sure that with more effort we can make it even better." }, { "code": null, "e": 11334, "s": 11146, "text": "I am not sharing code snippet for training the model as it’s same as shown in above snippets; only with right parameters. You can find all the complete programs on my Github profile here." } ]
Stock Analysis in Python. Exploring financial data with... | by Will Koehrsen | Towards Data Science
Exploring financial data with object-oriented programming and additive models It’s easy to get carried away with the wealth of data and free open-source tools available for data science. After spending a little bit of time with the quandl financial library and the prophet modeling library, I decided to try some simple stock data exploration. Several days and 1000 lines of Python later, I ended up with a complete stock analysis and prediction tool. Although I am not confident (or foolish) enough to use it to invest in individual stocks, I learned a ton of Python in the process and in the spirit of open-source, want to share my results and code so others can benefit. This article will show how to use Stocker, a Python class-based tool for stock analysis and prediction (the name was originally arbitrary, but I decided after the fact it nicely stands for “stock explorer”). I had tried several times to conquer classes, the foundation of object-oriented programming in Python, but as with most programming topics, they never quite made sense to me when I read the books. It was only when I was deep in a project faced with a problem I had not solved before that the concept finally clicked, showing once again that experience beats theoretical explanations! In addition to an exploration of Stocker, we will touch on some important topics including the basics of a Python class and additive models. For anyone wanting to use Stocker, the complete code can be found on GitHub along with documentation for usage. Stocker was designed to be easy to use (even for those new to Python), and I encourage anyone reading to try it out. Now, let’s take a look at the analysis capabilities of Stocker! After installing the required libraries, the first thing we do is import the Stocker class into our Python session. We can do this from an interactive Python session or a Jupyter Notebook started in the directory with the script. from stocker import Stocker We now have the Stocker class in our Python session, and we can use it to create an instance of the class. In Python, an instance of a class is called an object, and the act of creating an object is sometimes called instantiation or construction. In order to make a Stocker object we need to pass in the name of a valid stock ticker (bold indicates output). microsoft = Stocker('MSFT')MSFT Stocker Initialized. Data covers 1986-03-13 to 2018-01-16. Now, we have a microsoftobject with all the properties of the Stocker class. Stocker is built on the quandl WIKI database which gives us access to over 3000 US stocks with years of daily price data (full list). For this example, we will stick to Microsoft data. Although Microsoft might be seen as the opposite of open-source, they have recently made some changes that make me optimist they are embracing the open-source community (including Python). A class in Python is comprised of two main parts: attributes and methods. Without going into too much detail, attributes are values or data associated either with the class as a whole or with specific instances (objects) of the class. Methods are functions contained in the class which can act on that data. One attribute of a Stocker object is stock data for a specific company that is attribute is associated with the object when we construct it. We can access the attribute and assign it to another variable for inspection: # Stock is an attribute of the microsoft objectstock_history = microsoft.stockstock_history.head() The benefit of a Python class is that the methods (functions) and the data they act on are associated with the same object. We can use a method of the Stocker object to plot the entire history of the stock. # A method (function) requires parenthesesmicrosoft.plot_stock()Maximum Adj. Close = 89.58 on 2018-01-12.Minimum Adj. Close = 0.06 on 1986-03-24.Current Adj. Close = 88.35. The default value plotted is the Adjusted Closing price, which accounts for splits in the stock (when one stock is split into multiple stocks, say 2, with each new stock worth 1/2 of the original price). This is a pretty basic plot that we could have found from a Google Search, but there is something satisfying about doing it ourselves in a few lines of Python! The plot_stockfunction has a number of optional arguments. By default, this method plots the Adjusted Closing price for the entire date range, but we can choose the range, the stats to plot, and the type of plot. For example, if we want to compare the Daily Change in price with the Adjusted Volume (number of shares) traded, we can specify those in the function call. microsoft.plot_stock(start_date = '2000-01-03', end_date = '2018-01-16', stats = ['Daily Change', 'Adj. Volume'], plot_type='pct')Maximum Daily Change = 2.08 on 2008-10-13.Minimum Daily Change = -3.34 on 2017-12-04.Current Daily Change = -1.75.Maximum Adj. Volume = 591052200.00 on 2006-04-28.Minimum Adj. Volume = 7425503.00 on 2017-11-24.Current Adj. Volume = 35945428.00. Notice the y-axis is in percentage change relative to the average value for the statistic. This scale is necessary because the daily volume is originally in shares, with a range in the hundreds of millions, while daily price change typically is a few dollars! By converting to percentage change we can look at both datasets on a similar scale. The plot shows there is no correlation between the number of shares traded and the daily change in price. This is surprising as we might have expected more shares to be traded on days with larger price changes as people rush to take advantage of the swings. However, the only real trend seems to be that the volume traded decreases over time. There is also a significant decrease in price on December 4, 2017 that we could try to correlate with news stories about Microsoft. A quick news search for December 3 yields the following: There certainly does not seem to be any indication that Microsoft stock is due for its largest price decrease in 10 years the next day! In fact, if we were playing the stock market based on news, we might have been tempted to buy stock because a deal with the NFL (second result) sounds like a positive! Using plot_stock,we can investigate any of the quantities in the data across any date range and look for correlations with real-world events (if there are any). For now, we will move on to one of the more enjoyable parts of Stocker: making fake money! Let’s pretend for a moment we had the presence of mind to invest in 100 shares of Microsoft at the company’s Initial Public Offering (IPO). How much richer would we be now? microsoft.buy_and_hold(start_date='1986-03-13', end_date='2018-01-16', nshares=100)MSFT Total buy and hold profit from 1986-03-13 to 2018-01-16 for 100 shares = $8829.11 In addition to making us feel better, using these results will allow us to plan our trips back in time to maximize profits. If we are feeling too confident, we can try to tweak the results to lose money: microsoft.buy_and_hold(start_date='1999-01-05', end_date='2002-01-03', nshares=100)MSFT Total buy and hold profit from 1999-01-05 to 2002-01-03 for 100 shares = $-56.92 Surprisingly, it is possible to lose money in the stock market! Additive models are a powerful tool for analyzing and predicting time series, one of the most common types of real world data. The concept is straightforward: represent a time series as a combination of patterns on different time scales and an overall trend. We know the long-term trend of Microsoft stock is a steady increase, but there could also be patterns on a yearly or daily basis, such as an increase every Tuesday, that would be economically beneficial to know. A great library for analyzing time series with daily observations (such as stocks) is Prophet, developed by Facebook. Stocker does all the modeling work with Prophet behind the scenes for us, so we can use a simple method call to create and inspect a model. model, model_data = microsoft.create_prophet_model() The additive model smooths out the noise in the data, which is why the modeled line does not exactly line up with the observations. Prophet models also calculate uncertainty, an essential part of modeling as we can never be sure of our predictions when dealing with fluctuating real life processes. We can also use a prophet model to make predictions for the future, but for now we are more concerned with past data. Notice that this method call returned two objects, a model and some data, which we assigned to variables. We now use these variables to plot the time series components. # model and model_data are from previous method callmodel.plot_components(model_data)plt.show() The overall trend is a definitive increase over the past three years. There also appears to be a noticeable yearly pattern (bottom graph), with prices bottoming out in September and October and reaching a peak in November and January. As the time-scale decreases, the data gets noisier. Over the course of a typical month, there is more signal than noise! If we believe there might be a weekly pattern, we can add that in to the prophet model by changing the weekly_seasonalityattribute of the Stocker object: print(microsoft.weekly_seasonality)microsoft.weekly_seasonality = Trueprint(microsoft.weekly_seasonality)False True The default value for weekly_seasonalityis False, but we changed the value to include a weekly pattern in our model. We then make another call to create_prophet_modeland graph the resulting components. Below is the weekly seasonality from the new model. We can ignore the weekends because the price only changes over the week (in reality the price changes by a small amount during after-hours training but it does not affect our analysis). Unfortunately, there is not a trend over the week that we can use and before we continue modeling, we will turn off the weekly seasonality. This behavior is expected: with stock data, as the time scale decreases, the noise starts to wash out the signal. On a day-to-day basis, the movements of stocks are essentially random, and it is only by zooming out to the yearly scale that we can see trends. Hopefully this serves as a good reminder of why not to play the daily stock game! Changepoints occur when a time-series goes from increasing to decreasing or vice versa (in a more rigorous sense, they are located where the change in the rate of the time series is greatest). These times are extremely important because knowing when a stock will reach a peak or is about to take off could have significant economic benefits. Identifying the causes of changepoints might let us predict future swings in the value of a stock. The Stocker object can automatically find the 10 largest changepoints for us. microsoft.changepoint_date_analysis()Changepoints sorted by slope rate of change (2nd derivative): Date Adj. Close delta48 2015-03-30 38.238066 2.580296337 2016-05-20 48.886934 2.231580409 2016-09-01 55.966886 -2.05396572 2015-05-04 45.034285 -2.040387313 2016-04-18 54.141111 -1.936257 The changepoints tend to line up with peaks and valleys in the stock price. Prophet only finds changepoints in the first 80% of the data, but nonetheless, these results are useful because we can attempt to correlate them with real-world events. We could repeat what we did earlier and manually search for Google News around these dates, but I thought it would be preferable if Stocker did that for us. You might have seen the Google Search Trends tool which allows you to see the popularity of any search term over time in Google searches. Stocker can automatically retrieve this data for any search term we specify and plot the result on the original data. To find and graph the frequency of a search term, we modify the previous method call. # same method but with a search termmicrosoft.changepoint_date_analysis(search = 'Microsoft profit')Top Related Queries: query value0 microsoft non profit 1001 microsoft office 552 apple 303 microsoft 365 304 microsoft office 365 20 Rising Related Queries: query value0 microsoft 365 1201 microsoft office 365 902 microsoft profit 2014 70 In addition to graphing the relative search frequency, Stocker displays the top related queries and the top rising queries for the date range of the graph. On the graph, the y-axis is normalized between 0 and 1 by dividing the values by their maximums, allowing us to compare two variables with different scales. From the figure, there does not appear to be a correlation between searches for “Microsoft profit” and the stock price of Microsoft. Had we found a correlation, there would still be the question of causation. We would not know if searches or news caused the price to change, or if the change in price caused the searches. There might be some useful information to be found, but there are also many chance correlations. (For a humorous take on such random relationships, check out spurious correlations). Feel free to try out some different terms to see if you can find any interesting trends! microsoft.changepoint_date_analysis(search = 'Microsoft Office') Looks like declining searches for Office leads to increasing stock prices. Maybe someone should let Microsoft know. We have only explored the first half of Stocker capabilities. The second half is designed for forecasting, or predicting future stock price. Although this might be a futile exercise (or at least will not pay off), there is still plenty to learn in the process! Stay tuned for a future article on prediction, or get started predicting with Stocker on your own (check out the documentation for details). For now, I’ll leave you with one more image. # specify number of days in future to make a predictionmodel, future = microsoft.create_prophet_model(days=180)Predicted Price on 2018-07-15 = $97.67 Although all the capabilities of Stocker might already be publically available, the process of creating this tool was enjoyable, and more importantly, taught me more about data science, Python, and the stock market than any college course could. We live in an incredible age of democratized knowledge where anyone can learn about programming or even state of the art fields like machine learning without formal instruction. If you have an idea for a project but think you do not know enough or find out it has been done before, don’t let that stop you. You might develop a better solution and even if you don’t, you’ll be better off and know more than if you had never started! As always, I welcome constructive criticism and feedback. I can be reached on twitter at @koehrsen_will.
[ { "code": null, "e": 250, "s": 172, "text": "Exploring financial data with object-oriented programming and additive models" }, { "code": null, "e": 846, "s": 250, "text": "It’s easy to get carried away with the wealth of data and free open-source tools available for data science. After spending a little bit of time with the quandl financial library and the prophet modeling library, I decided to try some simple stock data exploration. Several days and 1000 lines of Python later, I ended up with a complete stock analysis and prediction tool. Although I am not confident (or foolish) enough to use it to invest in individual stocks, I learned a ton of Python in the process and in the spirit of open-source, want to share my results and code so others can benefit." }, { "code": null, "e": 1872, "s": 846, "text": "This article will show how to use Stocker, a Python class-based tool for stock analysis and prediction (the name was originally arbitrary, but I decided after the fact it nicely stands for “stock explorer”). I had tried several times to conquer classes, the foundation of object-oriented programming in Python, but as with most programming topics, they never quite made sense to me when I read the books. It was only when I was deep in a project faced with a problem I had not solved before that the concept finally clicked, showing once again that experience beats theoretical explanations! In addition to an exploration of Stocker, we will touch on some important topics including the basics of a Python class and additive models. For anyone wanting to use Stocker, the complete code can be found on GitHub along with documentation for usage. Stocker was designed to be easy to use (even for those new to Python), and I encourage anyone reading to try it out. Now, let’s take a look at the analysis capabilities of Stocker!" }, { "code": null, "e": 2102, "s": 1872, "text": "After installing the required libraries, the first thing we do is import the Stocker class into our Python session. We can do this from an interactive Python session or a Jupyter Notebook started in the directory with the script." }, { "code": null, "e": 2130, "s": 2102, "text": "from stocker import Stocker" }, { "code": null, "e": 2488, "s": 2130, "text": "We now have the Stocker class in our Python session, and we can use it to create an instance of the class. In Python, an instance of a class is called an object, and the act of creating an object is sometimes called instantiation or construction. In order to make a Stocker object we need to pass in the name of a valid stock ticker (bold indicates output)." }, { "code": null, "e": 2579, "s": 2488, "text": "microsoft = Stocker('MSFT')MSFT Stocker Initialized. Data covers 1986-03-13 to 2018-01-16." }, { "code": null, "e": 3030, "s": 2579, "text": "Now, we have a microsoftobject with all the properties of the Stocker class. Stocker is built on the quandl WIKI database which gives us access to over 3000 US stocks with years of daily price data (full list). For this example, we will stick to Microsoft data. Although Microsoft might be seen as the opposite of open-source, they have recently made some changes that make me optimist they are embracing the open-source community (including Python)." }, { "code": null, "e": 3557, "s": 3030, "text": "A class in Python is comprised of two main parts: attributes and methods. Without going into too much detail, attributes are values or data associated either with the class as a whole or with specific instances (objects) of the class. Methods are functions contained in the class which can act on that data. One attribute of a Stocker object is stock data for a specific company that is attribute is associated with the object when we construct it. We can access the attribute and assign it to another variable for inspection:" }, { "code": null, "e": 3656, "s": 3557, "text": "# Stock is an attribute of the microsoft objectstock_history = microsoft.stockstock_history.head()" }, { "code": null, "e": 3863, "s": 3656, "text": "The benefit of a Python class is that the methods (functions) and the data they act on are associated with the same object. We can use a method of the Stocker object to plot the entire history of the stock." }, { "code": null, "e": 4036, "s": 3863, "text": "# A method (function) requires parenthesesmicrosoft.plot_stock()Maximum Adj. Close = 89.58 on 2018-01-12.Minimum Adj. Close = 0.06 on 1986-03-24.Current Adj. Close = 88.35." }, { "code": null, "e": 4240, "s": 4036, "text": "The default value plotted is the Adjusted Closing price, which accounts for splits in the stock (when one stock is split into multiple stocks, say 2, with each new stock worth 1/2 of the original price)." }, { "code": null, "e": 4769, "s": 4240, "text": "This is a pretty basic plot that we could have found from a Google Search, but there is something satisfying about doing it ourselves in a few lines of Python! The plot_stockfunction has a number of optional arguments. By default, this method plots the Adjusted Closing price for the entire date range, but we can choose the range, the stats to plot, and the type of plot. For example, if we want to compare the Daily Change in price with the Adjusted Volume (number of shares) traded, we can specify those in the function call." }, { "code": null, "e": 5147, "s": 4769, "text": "microsoft.plot_stock(start_date = '2000-01-03', end_date = '2018-01-16', stats = ['Daily Change', 'Adj. Volume'], plot_type='pct')Maximum Daily Change = 2.08 on 2008-10-13.Minimum Daily Change = -3.34 on 2017-12-04.Current Daily Change = -1.75.Maximum Adj. Volume = 591052200.00 on 2006-04-28.Minimum Adj. Volume = 7425503.00 on 2017-11-24.Current Adj. Volume = 35945428.00." }, { "code": null, "e": 6023, "s": 5147, "text": "Notice the y-axis is in percentage change relative to the average value for the statistic. This scale is necessary because the daily volume is originally in shares, with a range in the hundreds of millions, while daily price change typically is a few dollars! By converting to percentage change we can look at both datasets on a similar scale. The plot shows there is no correlation between the number of shares traded and the daily change in price. This is surprising as we might have expected more shares to be traded on days with larger price changes as people rush to take advantage of the swings. However, the only real trend seems to be that the volume traded decreases over time. There is also a significant decrease in price on December 4, 2017 that we could try to correlate with news stories about Microsoft. A quick news search for December 3 yields the following:" }, { "code": null, "e": 6327, "s": 6023, "text": "There certainly does not seem to be any indication that Microsoft stock is due for its largest price decrease in 10 years the next day! In fact, if we were playing the stock market based on news, we might have been tempted to buy stock because a deal with the NFL (second result) sounds like a positive!" }, { "code": null, "e": 6579, "s": 6327, "text": "Using plot_stock,we can investigate any of the quantities in the data across any date range and look for correlations with real-world events (if there are any). For now, we will move on to one of the more enjoyable parts of Stocker: making fake money!" }, { "code": null, "e": 6752, "s": 6579, "text": "Let’s pretend for a moment we had the presence of mind to invest in 100 shares of Microsoft at the company’s Initial Public Offering (IPO). How much richer would we be now?" }, { "code": null, "e": 6945, "s": 6752, "text": "microsoft.buy_and_hold(start_date='1986-03-13', end_date='2018-01-16', nshares=100)MSFT Total buy and hold profit from 1986-03-13 to 2018-01-16 for 100 shares = $8829.11" }, { "code": null, "e": 7069, "s": 6945, "text": "In addition to making us feel better, using these results will allow us to plan our trips back in time to maximize profits." }, { "code": null, "e": 7149, "s": 7069, "text": "If we are feeling too confident, we can try to tweak the results to lose money:" }, { "code": null, "e": 7340, "s": 7149, "text": "microsoft.buy_and_hold(start_date='1999-01-05', end_date='2002-01-03', nshares=100)MSFT Total buy and hold profit from 1999-01-05 to 2002-01-03 for 100 shares = $-56.92" }, { "code": null, "e": 7404, "s": 7340, "text": "Surprisingly, it is possible to lose money in the stock market!" }, { "code": null, "e": 8133, "s": 7404, "text": "Additive models are a powerful tool for analyzing and predicting time series, one of the most common types of real world data. The concept is straightforward: represent a time series as a combination of patterns on different time scales and an overall trend. We know the long-term trend of Microsoft stock is a steady increase, but there could also be patterns on a yearly or daily basis, such as an increase every Tuesday, that would be economically beneficial to know. A great library for analyzing time series with daily observations (such as stocks) is Prophet, developed by Facebook. Stocker does all the modeling work with Prophet behind the scenes for us, so we can use a simple method call to create and inspect a model." }, { "code": null, "e": 8186, "s": 8133, "text": "model, model_data = microsoft.create_prophet_model()" }, { "code": null, "e": 8772, "s": 8186, "text": "The additive model smooths out the noise in the data, which is why the modeled line does not exactly line up with the observations. Prophet models also calculate uncertainty, an essential part of modeling as we can never be sure of our predictions when dealing with fluctuating real life processes. We can also use a prophet model to make predictions for the future, but for now we are more concerned with past data. Notice that this method call returned two objects, a model and some data, which we assigned to variables. We now use these variables to plot the time series components." }, { "code": null, "e": 8868, "s": 8772, "text": "# model and model_data are from previous method callmodel.plot_components(model_data)plt.show()" }, { "code": null, "e": 9378, "s": 8868, "text": "The overall trend is a definitive increase over the past three years. There also appears to be a noticeable yearly pattern (bottom graph), with prices bottoming out in September and October and reaching a peak in November and January. As the time-scale decreases, the data gets noisier. Over the course of a typical month, there is more signal than noise! If we believe there might be a weekly pattern, we can add that in to the prophet model by changing the weekly_seasonalityattribute of the Stocker object:" }, { "code": null, "e": 9494, "s": 9378, "text": "print(microsoft.weekly_seasonality)microsoft.weekly_seasonality = Trueprint(microsoft.weekly_seasonality)False True" }, { "code": null, "e": 9748, "s": 9494, "text": "The default value for weekly_seasonalityis False, but we changed the value to include a weekly pattern in our model. We then make another call to create_prophet_modeland graph the resulting components. Below is the weekly seasonality from the new model." }, { "code": null, "e": 10415, "s": 9748, "text": "We can ignore the weekends because the price only changes over the week (in reality the price changes by a small amount during after-hours training but it does not affect our analysis). Unfortunately, there is not a trend over the week that we can use and before we continue modeling, we will turn off the weekly seasonality. This behavior is expected: with stock data, as the time scale decreases, the noise starts to wash out the signal. On a day-to-day basis, the movements of stocks are essentially random, and it is only by zooming out to the yearly scale that we can see trends. Hopefully this serves as a good reminder of why not to play the daily stock game!" }, { "code": null, "e": 10934, "s": 10415, "text": "Changepoints occur when a time-series goes from increasing to decreasing or vice versa (in a more rigorous sense, they are located where the change in the rate of the time series is greatest). These times are extremely important because knowing when a stock will reach a peak or is about to take off could have significant economic benefits. Identifying the causes of changepoints might let us predict future swings in the value of a stock. The Stocker object can automatically find the 10 largest changepoints for us." }, { "code": null, "e": 11249, "s": 10934, "text": "microsoft.changepoint_date_analysis()Changepoints sorted by slope rate of change (2nd derivative): Date Adj. Close delta48 2015-03-30 38.238066 2.580296337 2016-05-20 48.886934 2.231580409 2016-09-01 55.966886 -2.05396572 2015-05-04 45.034285 -2.040387313 2016-04-18 54.141111 -1.936257" }, { "code": null, "e": 11993, "s": 11249, "text": "The changepoints tend to line up with peaks and valleys in the stock price. Prophet only finds changepoints in the first 80% of the data, but nonetheless, these results are useful because we can attempt to correlate them with real-world events. We could repeat what we did earlier and manually search for Google News around these dates, but I thought it would be preferable if Stocker did that for us. You might have seen the Google Search Trends tool which allows you to see the popularity of any search term over time in Google searches. Stocker can automatically retrieve this data for any search term we specify and plot the result on the original data. To find and graph the frequency of a search term, we modify the previous method call." }, { "code": null, "e": 12444, "s": 11993, "text": "# same method but with a search termmicrosoft.changepoint_date_analysis(search = 'Microsoft profit')Top Related Queries: query value0 microsoft non profit 1001 microsoft office 552 apple 303 microsoft 365 304 microsoft office 365 20 Rising Related Queries: query value0 microsoft 365 1201 microsoft office 365 902 microsoft profit 2014 70" }, { "code": null, "e": 12890, "s": 12444, "text": "In addition to graphing the relative search frequency, Stocker displays the top related queries and the top rising queries for the date range of the graph. On the graph, the y-axis is normalized between 0 and 1 by dividing the values by their maximums, allowing us to compare two variables with different scales. From the figure, there does not appear to be a correlation between searches for “Microsoft profit” and the stock price of Microsoft." }, { "code": null, "e": 13350, "s": 12890, "text": "Had we found a correlation, there would still be the question of causation. We would not know if searches or news caused the price to change, or if the change in price caused the searches. There might be some useful information to be found, but there are also many chance correlations. (For a humorous take on such random relationships, check out spurious correlations). Feel free to try out some different terms to see if you can find any interesting trends!" }, { "code": null, "e": 13415, "s": 13350, "text": "microsoft.changepoint_date_analysis(search = 'Microsoft Office')" }, { "code": null, "e": 13531, "s": 13415, "text": "Looks like declining searches for Office leads to increasing stock prices. Maybe someone should let Microsoft know." }, { "code": null, "e": 13978, "s": 13531, "text": "We have only explored the first half of Stocker capabilities. The second half is designed for forecasting, or predicting future stock price. Although this might be a futile exercise (or at least will not pay off), there is still plenty to learn in the process! Stay tuned for a future article on prediction, or get started predicting with Stocker on your own (check out the documentation for details). For now, I’ll leave you with one more image." }, { "code": null, "e": 14128, "s": 13978, "text": "# specify number of days in future to make a predictionmodel, future = microsoft.create_prophet_model(days=180)Predicted Price on 2018-07-15 = $97.67" }, { "code": null, "e": 14806, "s": 14128, "text": "Although all the capabilities of Stocker might already be publically available, the process of creating this tool was enjoyable, and more importantly, taught me more about data science, Python, and the stock market than any college course could. We live in an incredible age of democratized knowledge where anyone can learn about programming or even state of the art fields like machine learning without formal instruction. If you have an idea for a project but think you do not know enough or find out it has been done before, don’t let that stop you. You might develop a better solution and even if you don’t, you’ll be better off and know more than if you had never started!" } ]
MySQL query to count frequency of students with the same age?
You can use COUNT(*) along with GROUP BY for this. Let us first create a table − mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentAge int ); Query OK, 0 rows affected (0.59 sec) Insert records in the table using insert command − mysql> insert into DemoTable(StudentAge) values(16); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(StudentAge) values(17); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(StudentAge) values(18); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentAge) values(17); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentAge) values(17); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(StudentAge) values(17); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(StudentAge) values(18); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentAge) values(18); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(StudentAge) values(19); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentAge) values(19); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(StudentAge) values(16); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentAge) values(16); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(StudentAge) values(15); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select * from DemoTable; This will produce the following output − +-----------+------------+ | StudentId | StudentAge | +-----------+------------+ | 1 | 16 | | 2 | 17 | | 3 | 18 | | 4 | 17 | | 5 | 17 | | 6 | 17 | | 7 | 18 | | 8 | 18 | | 9 | 19 | | 10 | 19 | | 11 | 16 | | 12 | 16 | | 13 | 15 | +-----------+------------+ 13 rows in set (0.00 sec) Following is the query to count frequency − mysql> select StudentAge,count(*) AS `AgeFrequency` from DemoTable group by StudentAge; This will produce the following output − +------------+--------------+ | StudentAge | AgeFrequency | +------------+--------------+ | 16 | 3 | | 17 | 4 | | 18 | 3 | | 19 | 2 | | 15 | 1 | +------------+--------------+ 5 rows in set (0.05 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "You can use COUNT(*) along with GROUP BY for this. Let us first create a table −" }, { "code": null, "e": 1293, "s": 1143, "text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentAge int\n );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1344, "s": 1293, "text": "Insert records in the table using insert command −" }, { "code": null, "e": 2501, "s": 1344, "text": "mysql> insert into DemoTable(StudentAge) values(16);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable(StudentAge) values(17);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(StudentAge) values(18);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentAge) values(17);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentAge) values(17);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable(StudentAge) values(17);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable(StudentAge) values(18);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(StudentAge) values(18);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(StudentAge) values(19);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentAge) values(19);\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable(StudentAge) values(16);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentAge) values(16);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(StudentAge) values(15);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2561, "s": 2501, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2593, "s": 2561, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2634, "s": 2593, "text": "This will produce the following output −" }, { "code": null, "e": 3119, "s": 2634, "text": "+-----------+------------+\n| StudentId | StudentAge |\n+-----------+------------+\n| 1 | 16 |\n| 2 | 17 |\n| 3 | 18 |\n| 4 | 17 |\n| 5 | 17 |\n| 6 | 17 |\n| 7 | 18 |\n| 8 | 18 |\n| 9 | 19 |\n| 10 | 19 |\n| 11 | 16 |\n| 12 | 16 |\n| 13 | 15 |\n+-----------+------------+\n13 rows in set (0.00 sec)" }, { "code": null, "e": 3163, "s": 3119, "text": "Following is the query to count frequency −" }, { "code": null, "e": 3251, "s": 3163, "text": "mysql> select StudentAge,count(*) AS `AgeFrequency` from DemoTable group by StudentAge;" }, { "code": null, "e": 3292, "s": 3251, "text": "This will produce the following output −" }, { "code": null, "e": 3587, "s": 3292, "text": "+------------+--------------+\n| StudentAge | AgeFrequency |\n+------------+--------------+\n| 16 | 3 |\n| 17 | 4 |\n| 18 | 3 |\n| 19 | 2 |\n| 15 | 1 |\n+------------+--------------+\n5 rows in set (0.05 sec)" } ]
Java DOM Parser - Parse XML Document
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 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"?> <class> </class>"); 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 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": 2396, "s": 2323, "text": "Following are the steps used while parsing a document using JDOM Parser." }, { "code": null, "e": 2425, "s": 2396, "text": "Import XML-related packages." }, { "code": null, "e": 2446, "s": 2425, "text": "Create a SAXBuilder." }, { "code": null, "e": 2486, "s": 2446, "text": "Create a Document from a file or stream" }, { "code": null, "e": 2511, "s": 2486, "text": "Extract the root element" }, { "code": null, "e": 2530, "s": 2511, "text": "Examine attributes" }, { "code": null, "e": 2551, "s": 2530, "text": "Examine sub-elements" }, { "code": null, "e": 2619, "s": 2551, "text": "import org.w3c.dom.*;\nimport javax.xml.parsers.*;\nimport java.io.*;" }, { "code": null, "e": 2746, "s": 2619, "text": "DocumentBuilderFactory factory =\nDocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();" }, { "code": null, "e": 3010, "s": 2746, "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": 3056, "s": 3010, "text": "Element root = document.getDocumentElement();" }, { "code": null, "e": 3174, "s": 3056, "text": "//returns specific attribute\ngetAttribute(\"attributeName\");\n\n//returns a Map (table) of names/values\ngetAttributes();" }, { "code": null, "e": 3318, "s": 3174, "text": "//returns a list of subelements of specified name\ngetElementsByTagName(\"subelementName\");\n\n//returns a list of all child nodes\ngetChildNodes();" }, { "code": null, "e": 3369, "s": 3318, "text": "Here is the input xml file that we need to parse −" }, { "code": null, "e": 3920, "s": 3369, "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": 6080, "s": 3920, "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": 6122, "s": 6080, "text": "This would produce the following result −" }, { "code": null, "e": 6515, "s": 6122, "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": 6548, "s": 6515, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6564, "s": 6548, "text": " Malhar Lathkar" }, { "code": null, "e": 6597, "s": 6564, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6613, "s": 6597, "text": " Malhar Lathkar" }, { "code": null, "e": 6648, "s": 6613, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6662, "s": 6648, "text": " Anadi Sharma" }, { "code": null, "e": 6696, "s": 6662, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6710, "s": 6696, "text": " Tushar Kale" }, { "code": null, "e": 6747, "s": 6710, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6762, "s": 6747, "text": " Monica Mittal" }, { "code": null, "e": 6795, "s": 6762, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6814, "s": 6795, "text": " Arnab Chakraborty" }, { "code": null, "e": 6821, "s": 6814, "text": " Print" }, { "code": null, "e": 6832, "s": 6821, "text": " Add Notes" } ]
Build a Site Bookmark App With JavaScript by using Local Storage - GeeksforGeeks
25 Jan, 2021 In this article, we will create a Site Bookmark app using HTML, CSS, and JavaScript. This will help us to store links to our favorite websites without working with any database, and just using the local storage of our browser. Local Storage is known as the web storage API and allows us to store data on the client-side. Data in local storage is stored in form of strings and persists even after closing the session. Data can only be removed if the user manually deletes it. All the data stays on the client-side, thus there is a defined limitation regarding the length of the values, and we can currently store from 2 MB to 10 MB size of data depending upon the browser we use. Approach: The Bookmark App which we are designing can do the following: Add a new bookmark with the user’s typed name and a website link. Contain option of visiting the website Deleting the bookmark Then always save the bookmarks permanently on LocalStorage Glimpse of the project: File structure: index.html style.css main.js We will use HTML to design the web page structure or layout. This includes: Header Section: This includes the heading of our webpage. Here heading is “Site Bookmarker”. Container Section: It contains the form and bookmarks section. Form Section: It includes two input fields, for site name and link. It also contains one “save” button for submitting the form. Bookmarks Section: This section will contain all our saved bookmarks, and will change dynamically based on input. HTML <!DOCTYPE html><html lang="en"><head> <title>Site Bookmarker</title> <!-- link the CSS file here --> <link rel="stylesheet" type="text/css" href="style.css"> </head><body> <h1>Site Bookmarker</h1> <div class="container"> <!-- form to enter details of site --> <form class="form" action="#"> <div class="input-field"> <label for="site_name">Name</label> <input name="site_name" type="text" placeholder="site name"> </div> <div class="input-field"> <label for="url">URL</label> <input name="url" type="text" placeholder="https://www.example.com"> </div> <button class="save_button">Save</button> </form> <!-- section where bookmarks will be displayed --> <h2>Saved Bookmarks</h2> <div class="bookmarks"></div> </div> <!-- link the JavaScript file here --> <script src="./main.js"></script></body></html> CSS Styling: CSS is used to style the different portions and make them more visually appealing. The form and bookmarks section is displayed using the flex layout. Adequate padding and margin are given to each element. The text size, color of each element along with background color is such that it is easily readable by the user. The individual bookmark would be dynamically added or removed when required. CSS *{ box-sizing: border-box; font-family: sans-serif; } body{ margin: 0; padding: 0; background-color: #333333; } a{ text-decoration: none; color: #fff; } /*Styling title*/ h1{ width: 100%; height: 80px; text-align: center; line-height: 80px; margin: 0; padding: 0; background-color: #47CF73; letter-spacing: 2px; word-spacing: 8px; color: #000; } h2{ color: #47CF73; } .container{ width: 600px; min-height: 150px; background-color: #333333; margin: 0 auto; } /*Styling form section*/ .form{ width: 100%; height: auto; background-color: #555555; padding: 40px 50px; margin: 20px 0; } .input-field{ display: flex; flex-direction: column; align-items: center; margin-bottom: 15px; } .input-field input[type="text"]{ width: 250px; height: 25px; outline: none; border: none; background-color: transparent; border-bottom: 2px solid #47CF73; padding-left: 10px; color: #fff; } .input-field label{ color: #47CF73; font-weight: bold; margin-bottom: 5px; } .save_button{ display: block; margin: 0 auto; border: none; width: 70px; height: 25px; background-color: #47CF73; color: #000; cursor: pointer; outline: none; } /*Styling Bookmarks section*/ .bookmarks{ width: 100%; background-color: #555555; padding: 20px; } .bookmark{ display: flex; align-items: center; width: 300px; height: 40px; padding: 5px 20px; background-color: #FAFAFA; margin-bottom: 10px; background-color: #333333; } .bookmark span{ flex: 1; font-weight: bold; letter-spacing: 1.5px; color: #fff; } .bookmark .visit{ width: 50px; height: 25px; line-height: 25px; text-align: center; background-color: #47CF73; color: #000; border-radius: 5px; margin: 0 5px; } .bookmark .delete{ width: 60px; height: 25px; line-height: 25px; text-align: center; background-color: #F44336; border-radius: 5px; } Logic: The main logic of our app is implemented using JavaScript. There are several functions that work together for the app. Step 1 (Selecting all the elements and defining variables): The first thing we need is to get a reference for everything we need from the DOM. The required elements in the HTML layout are selected using the querySelector() method. This will grab “.bookmarks”, “.save_button”, and input fields like “site_name” and “url” from the DOM and stores them in corresponding variables. They are assigned variable names so that they could be easily accessed and modified. Also, defining bookmark objects for our local storage to hold all bookmarks. Javascript // Select the save buttonvar button = document.querySelector(".save_button"); // Select the input boxvar siteName = document.querySelector("[name='site_name']");var url = document.querySelector("[name='url']"); // Select the <div> with class="bookmarks"var bookmarksSection = document.querySelector(".bookmarks"); // Hold bookmarks in local storageif(typeof(localStorage.bookmark) == "undefined"){ localStorage.bookmark = "";} Step2 (Getting values and setting validation for submitting event in form): We have EventListener for the save button to listen for a click event on the form. Whenever a click event happens, the function will activate. Every time the form is submitted, the page will reload. So to stop that we call e.preventDefault(). We can get the user’s typed name and url from the siteName.value and url.value respectively. Some validation is included to ensure we’re not saving things twice and that our form is not empty. After all validation, pass the user typed value to addBookmark() function. Note: We can store items on localStorage using setItem() method which requires a key and a value. Here we are using “localStorage.bookmark” which automatically creates a bookmark as a key in our localStorage. Javascript // listen for form submit button.addEventListener("click", function(e){ // Prevent the page from reloading when submitting the form e.preventDefault(); let patterURL = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi; let arrayItems, check = false, adr, itemAdr; // Validation of form and URL if(siteName.value === ""){ alert("you must fill the siteName input"); } else if(url.value === ""){ alert("you must fill the url input"); } else if(!patterURL.test(url.value)){ alert("you must enter a valid url"); } else{ arrayItems = localStorage.bookmark.split(";"); adr = url.value; adr = adr.replace(/http:\/\/|https:\/\//i, ""); arrayItems.length--; // Check if website is already bookmarked for(item of arrayItems){ itemAdr = item.split(',')[1].replace(/http:\/\/|https:\/\//i,""); if(itemAdr == adr){ check = true; } } if(check == true){ alert("This website is already bookmarked"); } else{ // If all checks are correct,add bookmark to local storage localStorage.bookmark += `${siteName.value},${url.value};`; addBookmark(siteName.value, url.value); siteName.value = ""; url.value = ""; } }}); Step 3 (Add bookmarks to our webpage): This addBookmark() function will take the site name and url as its argument. Then: Constructs a new bookmark object. This object has a name, URL, and properties of visit and delete. Then it pushes that object into our bookmarks section of the HTML page. After this, we will call the fetchBookmark() function. This function is responsible for rendering each item to the screen. Javascript // Function to add the bookmark function addBookmark(name, url){ let dataLink = url; // After obtaining a bookmark, we display it in a div and add // a button to visit the link or to delete it if(!url.includes("http")){ url = "//" + url; } let item = `<div class="bookmark"> <span>${name}</span> <a class="visit" href="${url}" target="_blank" data-link='${dataLink}'>Visit</a> <a onclick="removeBookmark(this)" class="delete" href="#">delete</a> </div>`; bookmarksSection.innerHTML += item;} Step 4 (Rendering the saved bookmarks): Now we can add bookmarks to our app and store them in localStorage. But when we refresh the page or start a new session all bookmarks disappear from the webpage even if stored in localStorage. So we need to persist them by fetching the bookmarks from the localStorage, using the fetchBookmark() function. First, we will check if the defined bookmark key is empty or not. If it’s not empty then: We will create an array of all bookmarks using split() method. Next, will loop through each item inside. And for each bookmark, we will get the name and url. To display these items we will call the addBookmark() function. Javascript // function to render the saved bookmarks (function fetchBoookmark(){ if(typeof(localStorage.bookmark) != "undefined" && localStorage.bookmark !== ""){ let arrayItems = localStorage.bookmark.split(";"); arrayItems.length--; for(item of arrayItems){ let itemSpli = item.split(','); addBookmark(itemSpli[0], itemSpli[1]); } }})(); Step 5 (Deleting bookmarks): Visiting a link is straightforward, we simply follow the URL but to delete it, we’ll need to identify the specific URL in our localStorage and then remove it from our object. For that, we’ll write a removeBookmark() function. First, we’ll fetch all the bookmarks from localStorage and store them in an array. The splice() method is used to remove items from the array and will return the updated item(s). Also, we will use removeChild() method to remove child nodes from the parent node of bookmarks. Javascript // Function to remove the bookmark function removeBookmark(thisItem){ let arrayItems = [], index, item = thisItem.parentNode, itemURL = item.querySelector(".visit").dataset.link, itemName = item.querySelector("span").innerHTML; arrayItems = localStorage.bookmark.split(";"); for(i in arrayItems){ if(arrayItems[i] == `${itemName},${itemURL}`){ index = i; break; } } //update the localStorage index = arrayItems.indexOf(`${itemName},${itemURL}`); arrayItems.splice(index,1); localStorage.bookmark = arrayItems.join(";"); //update the bookmark Section bookmarksSection.removeChild(item);} Output: And there you have it, our Site Bookmarker app is ready. You can also see the stored bookmarks in localStorage, as shown below: This Site Bookmarker App contains the basic functionality of adding, storing and deleting using Local Storage. You can get creative and also add functionalities of the edit function, or create collections to store bookmarks using the nested list. If you like to know more about Local Storage and its features, you can visit the following site: Local and Session Storage Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc HTML5 Technical Scripter 2020 Articles CSS HTML JavaScript Project Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GTest Framework Asymptotic Notations and how to calculate them How to use gotoxy() in codeblocks? File globbing in Linux Data Link Layer in OSI Model Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26157, "s": 26129, "text": "\n25 Jan, 2021" }, { "code": null, "e": 26384, "s": 26157, "text": "In this article, we will create a Site Bookmark app using HTML, CSS, and JavaScript. This will help us to store links to our favorite websites without working with any database, and just using the local storage of our browser." }, { "code": null, "e": 26838, "s": 26384, "text": "Local Storage is known as the web storage API and allows us to store data on the client-side. Data in local storage is stored in form of strings and persists even after closing the session. Data can only be removed if the user manually deletes it. All the data stays on the client-side, thus there is a defined limitation regarding the length of the values, and we can currently store from 2 MB to 10 MB size of data depending upon the browser we use." }, { "code": null, "e": 26910, "s": 26838, "text": "Approach: The Bookmark App which we are designing can do the following:" }, { "code": null, "e": 26976, "s": 26910, "text": "Add a new bookmark with the user’s typed name and a website link." }, { "code": null, "e": 27015, "s": 26976, "text": "Contain option of visiting the website" }, { "code": null, "e": 27037, "s": 27015, "text": "Deleting the bookmark" }, { "code": null, "e": 27096, "s": 27037, "text": "Then always save the bookmarks permanently on LocalStorage" }, { "code": null, "e": 27120, "s": 27096, "text": "Glimpse of the project:" }, { "code": null, "e": 27136, "s": 27120, "text": "File structure:" }, { "code": null, "e": 27147, "s": 27136, "text": "index.html" }, { "code": null, "e": 27157, "s": 27147, "text": "style.css" }, { "code": null, "e": 27165, "s": 27157, "text": "main.js" }, { "code": null, "e": 27242, "s": 27165, "text": " We will use HTML to design the web page structure or layout. This includes:" }, { "code": null, "e": 27335, "s": 27242, "text": "Header Section: This includes the heading of our webpage. Here heading is “Site Bookmarker”." }, { "code": null, "e": 27398, "s": 27335, "text": "Container Section: It contains the form and bookmarks section." }, { "code": null, "e": 27526, "s": 27398, "text": "Form Section: It includes two input fields, for site name and link. It also contains one “save” button for submitting the form." }, { "code": null, "e": 27640, "s": 27526, "text": "Bookmarks Section: This section will contain all our saved bookmarks, and will change dynamically based on input." }, { "code": null, "e": 27645, "s": 27640, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Site Bookmarker</title> <!-- link the CSS file here --> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"> </head><body> <h1>Site Bookmarker</h1> <div class=\"container\"> <!-- form to enter details of site --> <form class=\"form\" action=\"#\"> <div class=\"input-field\"> <label for=\"site_name\">Name</label> <input name=\"site_name\" type=\"text\" placeholder=\"site name\"> </div> <div class=\"input-field\"> <label for=\"url\">URL</label> <input name=\"url\" type=\"text\" placeholder=\"https://www.example.com\"> </div> <button class=\"save_button\">Save</button> </form> <!-- section where bookmarks will be displayed --> <h2>Saved Bookmarks</h2> <div class=\"bookmarks\"></div> </div> <!-- link the JavaScript file here --> <script src=\"./main.js\"></script></body></html>", "e": 28593, "s": 27645, "text": null }, { "code": null, "e": 28690, "s": 28593, "text": " CSS Styling: CSS is used to style the different portions and make them more visually appealing." }, { "code": null, "e": 28757, "s": 28690, "text": "The form and bookmarks section is displayed using the flex layout." }, { "code": null, "e": 28812, "s": 28757, "text": "Adequate padding and margin are given to each element." }, { "code": null, "e": 28925, "s": 28812, "text": "The text size, color of each element along with background color is such that it is easily readable by the user." }, { "code": null, "e": 29002, "s": 28925, "text": "The individual bookmark would be dynamically added or removed when required." }, { "code": null, "e": 29006, "s": 29002, "text": "CSS" }, { "code": "*{ box-sizing: border-box; font-family: sans-serif; } body{ margin: 0; padding: 0; background-color: #333333; } a{ text-decoration: none; color: #fff; } /*Styling title*/ h1{ width: 100%; height: 80px; text-align: center; line-height: 80px; margin: 0; padding: 0; background-color: #47CF73; letter-spacing: 2px; word-spacing: 8px; color: #000; } h2{ color: #47CF73; } .container{ width: 600px; min-height: 150px; background-color: #333333; margin: 0 auto; } /*Styling form section*/ .form{ width: 100%; height: auto; background-color: #555555; padding: 40px 50px; margin: 20px 0; } .input-field{ display: flex; flex-direction: column; align-items: center; margin-bottom: 15px; } .input-field input[type=\"text\"]{ width: 250px; height: 25px; outline: none; border: none; background-color: transparent; border-bottom: 2px solid #47CF73; padding-left: 10px; color: #fff; } .input-field label{ color: #47CF73; font-weight: bold; margin-bottom: 5px; } .save_button{ display: block; margin: 0 auto; border: none; width: 70px; height: 25px; background-color: #47CF73; color: #000; cursor: pointer; outline: none; } /*Styling Bookmarks section*/ .bookmarks{ width: 100%; background-color: #555555; padding: 20px; } .bookmark{ display: flex; align-items: center; width: 300px; height: 40px; padding: 5px 20px; background-color: #FAFAFA; margin-bottom: 10px; background-color: #333333; } .bookmark span{ flex: 1; font-weight: bold; letter-spacing: 1.5px; color: #fff; } .bookmark .visit{ width: 50px; height: 25px; line-height: 25px; text-align: center; background-color: #47CF73; color: #000; border-radius: 5px; margin: 0 5px; } .bookmark .delete{ width: 60px; height: 25px; line-height: 25px; text-align: center; background-color: #F44336; border-radius: 5px; }", "e": 31056, "s": 29006, "text": null }, { "code": null, "e": 31182, "s": 31056, "text": "Logic: The main logic of our app is implemented using JavaScript. There are several functions that work together for the app." }, { "code": null, "e": 31242, "s": 31182, "text": "Step 1 (Selecting all the elements and defining variables):" }, { "code": null, "e": 31413, "s": 31242, "text": "The first thing we need is to get a reference for everything we need from the DOM. The required elements in the HTML layout are selected using the querySelector() method." }, { "code": null, "e": 31561, "s": 31413, "text": "This will grab “.bookmarks”, “.save_button”, and input fields like “site_name” and “url” from the DOM and stores them in corresponding variables." }, { "code": null, "e": 31646, "s": 31561, "text": "They are assigned variable names so that they could be easily accessed and modified." }, { "code": null, "e": 31723, "s": 31646, "text": "Also, defining bookmark objects for our local storage to hold all bookmarks." }, { "code": null, "e": 31734, "s": 31723, "text": "Javascript" }, { "code": "// Select the save buttonvar button = document.querySelector(\".save_button\"); // Select the input boxvar siteName = document.querySelector(\"[name='site_name']\");var url = document.querySelector(\"[name='url']\"); // Select the <div> with class=\"bookmarks\"var bookmarksSection = document.querySelector(\".bookmarks\"); // Hold bookmarks in local storageif(typeof(localStorage.bookmark) == \"undefined\"){ localStorage.bookmark = \"\";}", "e": 32165, "s": 31734, "text": null }, { "code": null, "e": 32241, "s": 32165, "text": "Step2 (Getting values and setting validation for submitting event in form):" }, { "code": null, "e": 32384, "s": 32241, "text": "We have EventListener for the save button to listen for a click event on the form. Whenever a click event happens, the function will activate." }, { "code": null, "e": 32484, "s": 32384, "text": "Every time the form is submitted, the page will reload. So to stop that we call e.preventDefault()." }, { "code": null, "e": 32577, "s": 32484, "text": "We can get the user’s typed name and url from the siteName.value and url.value respectively." }, { "code": null, "e": 32677, "s": 32577, "text": "Some validation is included to ensure we’re not saving things twice and that our form is not empty." }, { "code": null, "e": 32752, "s": 32677, "text": "After all validation, pass the user typed value to addBookmark() function." }, { "code": null, "e": 32961, "s": 32752, "text": "Note: We can store items on localStorage using setItem() method which requires a key and a value. Here we are using “localStorage.bookmark” which automatically creates a bookmark as a key in our localStorage." }, { "code": null, "e": 32972, "s": 32961, "text": "Javascript" }, { "code": "// listen for form submit button.addEventListener(\"click\", function(e){ // Prevent the page from reloading when submitting the form e.preventDefault(); let patterURL = /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)?/gi; let arrayItems, check = false, adr, itemAdr; // Validation of form and URL if(siteName.value === \"\"){ alert(\"you must fill the siteName input\"); } else if(url.value === \"\"){ alert(\"you must fill the url input\"); } else if(!patterURL.test(url.value)){ alert(\"you must enter a valid url\"); } else{ arrayItems = localStorage.bookmark.split(\";\"); adr = url.value; adr = adr.replace(/http:\\/\\/|https:\\/\\//i, \"\"); arrayItems.length--; // Check if website is already bookmarked for(item of arrayItems){ itemAdr = item.split(',')[1].replace(/http:\\/\\/|https:\\/\\//i,\"\"); if(itemAdr == adr){ check = true; } } if(check == true){ alert(\"This website is already bookmarked\"); } else{ // If all checks are correct,add bookmark to local storage localStorage.bookmark += `${siteName.value},${url.value};`; addBookmark(siteName.value, url.value); siteName.value = \"\"; url.value = \"\"; } }});", "e": 34305, "s": 32972, "text": null }, { "code": null, "e": 34427, "s": 34305, "text": "Step 3 (Add bookmarks to our webpage): This addBookmark() function will take the site name and url as its argument. Then:" }, { "code": null, "e": 34461, "s": 34427, "text": "Constructs a new bookmark object." }, { "code": null, "e": 34526, "s": 34461, "text": "This object has a name, URL, and properties of visit and delete." }, { "code": null, "e": 34598, "s": 34526, "text": "Then it pushes that object into our bookmarks section of the HTML page." }, { "code": null, "e": 34721, "s": 34598, "text": "After this, we will call the fetchBookmark() function. This function is responsible for rendering each item to the screen." }, { "code": null, "e": 34732, "s": 34721, "text": "Javascript" }, { "code": "// Function to add the bookmark function addBookmark(name, url){ let dataLink = url; // After obtaining a bookmark, we display it in a div and add // a button to visit the link or to delete it if(!url.includes(\"http\")){ url = \"//\" + url; } let item = `<div class=\"bookmark\"> <span>${name}</span> <a class=\"visit\" href=\"${url}\" target=\"_blank\" data-link='${dataLink}'>Visit</a> <a onclick=\"removeBookmark(this)\" class=\"delete\" href=\"#\">delete</a> </div>`; bookmarksSection.innerHTML += item;}", "e": 35328, "s": 34732, "text": null }, { "code": null, "e": 35561, "s": 35328, "text": "Step 4 (Rendering the saved bookmarks): Now we can add bookmarks to our app and store them in localStorage. But when we refresh the page or start a new session all bookmarks disappear from the webpage even if stored in localStorage." }, { "code": null, "e": 35673, "s": 35561, "text": "So we need to persist them by fetching the bookmarks from the localStorage, using the fetchBookmark() function." }, { "code": null, "e": 35764, "s": 35673, "text": "First, we will check if the defined bookmark key is empty or not. If it’s not empty then:" }, { "code": null, "e": 35827, "s": 35764, "text": "We will create an array of all bookmarks using split() method." }, { "code": null, "e": 35922, "s": 35827, "text": "Next, will loop through each item inside. And for each bookmark, we will get the name and url." }, { "code": null, "e": 35986, "s": 35922, "text": "To display these items we will call the addBookmark() function." }, { "code": null, "e": 35997, "s": 35986, "text": "Javascript" }, { "code": "// function to render the saved bookmarks (function fetchBoookmark(){ if(typeof(localStorage.bookmark) != \"undefined\" && localStorage.bookmark !== \"\"){ let arrayItems = localStorage.bookmark.split(\";\"); arrayItems.length--; for(item of arrayItems){ let itemSpli = item.split(','); addBookmark(itemSpli[0], itemSpli[1]); } }})();", "e": 36351, "s": 35997, "text": null }, { "code": null, "e": 36555, "s": 36351, "text": "Step 5 (Deleting bookmarks): Visiting a link is straightforward, we simply follow the URL but to delete it, we’ll need to identify the specific URL in our localStorage and then remove it from our object." }, { "code": null, "e": 36606, "s": 36555, "text": "For that, we’ll write a removeBookmark() function." }, { "code": null, "e": 36689, "s": 36606, "text": "First, we’ll fetch all the bookmarks from localStorage and store them in an array." }, { "code": null, "e": 36785, "s": 36689, "text": "The splice() method is used to remove items from the array and will return the updated item(s)." }, { "code": null, "e": 36881, "s": 36785, "text": "Also, we will use removeChild() method to remove child nodes from the parent node of bookmarks." }, { "code": null, "e": 36892, "s": 36881, "text": "Javascript" }, { "code": "// Function to remove the bookmark function removeBookmark(thisItem){ let arrayItems = [], index, item = thisItem.parentNode, itemURL = item.querySelector(\".visit\").dataset.link, itemName = item.querySelector(\"span\").innerHTML; arrayItems = localStorage.bookmark.split(\";\"); for(i in arrayItems){ if(arrayItems[i] == `${itemName},${itemURL}`){ index = i; break; } } //update the localStorage index = arrayItems.indexOf(`${itemName},${itemURL}`); arrayItems.splice(index,1); localStorage.bookmark = arrayItems.join(\";\"); //update the bookmark Section bookmarksSection.removeChild(item);}", "e": 37538, "s": 36892, "text": null }, { "code": null, "e": 37674, "s": 37538, "text": "Output: And there you have it, our Site Bookmarker app is ready. You can also see the stored bookmarks in localStorage, as shown below:" }, { "code": null, "e": 37921, "s": 37674, "text": "This Site Bookmarker App contains the basic functionality of adding, storing and deleting using Local Storage. You can get creative and also add functionalities of the edit function, or create collections to store bookmarks using the nested list." }, { "code": null, "e": 38045, "s": 37921, "text": "If you like to know more about Local Storage and its features, you can visit the following site: Local and Session Storage" }, { "code": null, "e": 38182, "s": 38045, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 38191, "s": 38182, "text": "CSS-Misc" }, { "code": null, "e": 38201, "s": 38191, "text": "HTML-Misc" }, { "code": null, "e": 38207, "s": 38201, "text": "HTML5" }, { "code": null, "e": 38231, "s": 38207, "text": "Technical Scripter 2020" }, { "code": null, "e": 38240, "s": 38231, "text": "Articles" }, { "code": null, "e": 38244, "s": 38240, "text": "CSS" }, { "code": null, "e": 38249, "s": 38244, "text": "HTML" }, { "code": null, "e": 38260, "s": 38249, "text": "JavaScript" }, { "code": null, "e": 38268, "s": 38260, "text": "Project" }, { "code": null, "e": 38287, "s": 38268, "text": "Technical Scripter" }, { "code": null, "e": 38304, "s": 38287, "text": "Web Technologies" }, { "code": null, "e": 38309, "s": 38304, "text": "HTML" }, { "code": null, "e": 38407, "s": 38309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38423, "s": 38407, "text": "GTest Framework" }, { "code": null, "e": 38470, "s": 38423, "text": "Asymptotic Notations and how to calculate them" }, { "code": null, "e": 38505, "s": 38470, "text": "How to use gotoxy() in codeblocks?" }, { "code": null, "e": 38528, "s": 38505, "text": "File globbing in Linux" }, { "code": null, "e": 38557, "s": 38528, "text": "Data Link Layer in OSI Model" }, { "code": null, "e": 38619, "s": 38557, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38669, "s": 38619, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 38717, "s": 38669, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 38775, "s": 38717, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Introduction to MATLAB - GeeksforGeeks
14 Oct, 2019 MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces. Getting started with MATLAB:It is both a programming language as well as a programming environment. It allows the computation of statements in the command window itself. Command Window:In this window one must type and immediately execute the statements, as it requires quick prototyping. These statements cannot be saved. Thus, this is can be used for small, easily executable programs. Editor (Script):In this window one can execute larger programs with multiple statements, and complex functions These can be saved and are done with the file extension ‘.m ‘ Workspace:In this window the values of the variables that are created in the course of the program (in the editor) are displayed. This window displays the exact location(path) of the program file being created. MATLAB Library comes with a set of many inbuilt functions. These functions mostly perform mathematical operations like sine, cosine and tangent. They perform more complex functions too like finding the inverse and determinant of a matrix, cross product and dot product Although MATLAB is encoded in C, C++ and Java, it is a lot easier to implement than these three languages. For example, unlike the other three, no header files need to be initialised in the beginning of the document and for declaring a variable, the data type need not be provided. It provides an easier alternative for vector operations. They can be performed using one command instead of multiple statements in a for or while loop. Some of the basic functions in MATLAB and their uses are listed below: Writing a MATLAB program: Using Command Window:Only one statement can be typed and executed at a time. It executes the statement when the enter key is pressed. This is mostly used for simple calculations.Note: ans is a default variable created by MATLAB that stores the output of the given computation.Using Editor:Multiple lines of code can be written here and only after pressing the run button (or F5) will the code be executed. It is always a good practice to write clc, clear and close all in the beginning of the program.Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a commentVector Operations:Operations such as addition, subtraction, multiplication and division can be done using a single command instead of multiple loops Using Command Window:Only one statement can be typed and executed at a time. It executes the statement when the enter key is pressed. This is mostly used for simple calculations.Note: ans is a default variable created by MATLAB that stores the output of the given computation. Note: ans is a default variable created by MATLAB that stores the output of the given computation. Using Editor:Multiple lines of code can be written here and only after pressing the run button (or F5) will the code be executed. It is always a good practice to write clc, clear and close all in the beginning of the program.Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a comment Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a comment Vector Operations:Operations such as addition, subtraction, multiplication and division can be done using a single command instead of multiple loops We can also extract separate rows and columns by using the colon(:) operator. Consider a matrix A of size 3X3. The following commands can be used to extract rows and columns from Matrix A Plotting in MATLAB:The MATLAB graphics system consists of high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level commands that allows to fully customize the appearance of graphics as well as to build complete Graphical User Interfaces. Given below is a code for plotting a Parabola: x = 0:0.5:10; %Indicates that x varies from 0 to 10 with intervals of 0.5 y = x>^2; %Indicates that square of each element in x is stored in y plot(x, y)%plotting x and y xlabel(X)%naming x axis as x ylabel(Y)%naming y axis as y title('Graph of y=x^2')%Title of the graph This code will give the following graph: You can change the color of the graph by adding another statement in the plot command. For example, plot(x, y, ‘r’) will give the graph line in red. Graphs such as sine, cosine and other trigonometric functions’ curve can also be plotted. The code for sine curve is given below: x = 0:pi/100:2*pi; y = sin(x); plot(x, y, ‘g’)%Will give the graph line in green. In conclusion, MATLAB is a very user friendly language and it is also easy to understand.It’s library is equipped with functions that help us perform a variety of mathematical functions. Image-Processing MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example System Design Tutorial Copying Files to and from Docker Containers Python | Decision tree implementation ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction
[ { "code": null, "e": 25827, "s": 25799, "text": "\n14 Oct, 2019" }, { "code": null, "e": 26162, "s": 25827, "text": "MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces." }, { "code": null, "e": 26332, "s": 26162, "text": "Getting started with MATLAB:It is both a programming language as well as a programming environment. It allows the computation of statements in the command window itself." }, { "code": null, "e": 26549, "s": 26332, "text": "Command Window:In this window one must type and immediately execute the statements, as it requires quick prototyping. These statements cannot be saved. Thus, this is can be used for small, easily executable programs." }, { "code": null, "e": 26722, "s": 26549, "text": "Editor (Script):In this window one can execute larger programs with multiple statements, and complex functions These can be saved and are done with the file extension ‘.m ‘" }, { "code": null, "e": 26852, "s": 26722, "text": "Workspace:In this window the values of the variables that are created in the course of the program (in the editor) are displayed." }, { "code": null, "e": 26933, "s": 26852, "text": "This window displays the exact location(path) of the program file being created." }, { "code": null, "e": 27202, "s": 26933, "text": "MATLAB Library comes with a set of many inbuilt functions. These functions mostly perform mathematical operations like sine, cosine and tangent. They perform more complex functions too like finding the inverse and determinant of a matrix, cross product and dot product" }, { "code": null, "e": 27636, "s": 27202, "text": "Although MATLAB is encoded in C, C++ and Java, it is a lot easier to implement than these three languages. For example, unlike the other three, no header files need to be initialised in the beginning of the document and for declaring a variable, the data type need not be provided. It provides an easier alternative for vector operations. They can be performed using one command instead of multiple statements in a for or while loop." }, { "code": null, "e": 27707, "s": 27636, "text": "Some of the basic functions in MATLAB and their uses are listed below:" }, { "code": null, "e": 27733, "s": 27707, "text": "Writing a MATLAB program:" }, { "code": null, "e": 28590, "s": 27733, "text": "Using Command Window:Only one statement can be typed and executed at a time. It executes the statement when the enter key is pressed. This is mostly used for simple calculations.Note: ans is a default variable created by MATLAB that stores the output of the given computation.Using Editor:Multiple lines of code can be written here and only after pressing the run button (or F5) will the code be executed. It is always a good practice to write clc, clear and close all in the beginning of the program.Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a commentVector Operations:Operations such as addition, subtraction, multiplication and division can be done using a single command instead of multiple loops" }, { "code": null, "e": 28867, "s": 28590, "text": "Using Command Window:Only one statement can be typed and executed at a time. It executes the statement when the enter key is pressed. This is mostly used for simple calculations.Note: ans is a default variable created by MATLAB that stores the output of the given computation." }, { "code": null, "e": 28966, "s": 28867, "text": "Note: ans is a default variable created by MATLAB that stores the output of the given computation." }, { "code": null, "e": 29399, "s": 28966, "text": "Using Editor:Multiple lines of code can be written here and only after pressing the run button (or F5) will the code be executed. It is always a good practice to write clc, clear and close all in the beginning of the program.Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a comment" }, { "code": null, "e": 29607, "s": 29399, "text": "Note: Statements ending with a semicolon will not be displayed in the command window, however, their values will be displayed in the workspace.Any statement followed by % in MATLAB is considered as a comment" }, { "code": null, "e": 29756, "s": 29607, "text": "Vector Operations:Operations such as addition, subtraction, multiplication and division can be done using a single command instead of multiple loops" }, { "code": null, "e": 29944, "s": 29756, "text": "We can also extract separate rows and columns by using the colon(:) operator. Consider a matrix A of size 3X3. The following commands can be used to extract rows and columns from Matrix A" }, { "code": null, "e": 30290, "s": 29944, "text": "Plotting in MATLAB:The MATLAB graphics system consists of high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level commands that allows to fully customize the appearance of graphics as well as to build complete Graphical User Interfaces." }, { "code": null, "e": 30337, "s": 30290, "text": "Given below is a code for plotting a Parabola:" }, { "code": null, "e": 30351, "s": 30337, "text": "x = 0:0.5:10;" }, { "code": null, "e": 30411, "s": 30351, "text": "%Indicates that x varies from 0 to 10 with intervals of 0.5" }, { "code": null, "e": 30421, "s": 30411, "text": "y = x>^2;" }, { "code": null, "e": 30480, "s": 30421, "text": "%Indicates that square of each element in x is stored in y" }, { "code": null, "e": 30610, "s": 30480, "text": "plot(x, y)%plotting x and y\nxlabel(X)%naming x axis as x\nylabel(Y)%naming y axis as y\ntitle('Graph of y=x^2')%Title of the graph " }, { "code": null, "e": 30651, "s": 30610, "text": "This code will give the following graph:" }, { "code": null, "e": 30800, "s": 30651, "text": "You can change the color of the graph by adding another statement in the plot command. For example, plot(x, y, ‘r’) will give the graph line in red." }, { "code": null, "e": 30930, "s": 30800, "text": "Graphs such as sine, cosine and other trigonometric functions’ curve can also be plotted. The code for sine curve is given below:" }, { "code": null, "e": 30962, "s": 30930, "text": "x = 0:pi/100:2*pi;\ny = sin(x); " }, { "code": null, "e": 31013, "s": 30962, "text": "plot(x, y, ‘g’)%Will give the graph line in green." }, { "code": null, "e": 31200, "s": 31013, "text": "In conclusion, MATLAB is a very user friendly language and it is also easy to understand.It’s library is equipped with functions that help us perform a variety of mathematical functions." }, { "code": null, "e": 31217, "s": 31200, "text": "Image-Processing" }, { "code": null, "e": 31224, "s": 31217, "text": "MATLAB" }, { "code": null, "e": 31250, "s": 31224, "text": "Advanced Computer Subject" }, { "code": null, "e": 31348, "s": 31250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31371, "s": 31348, "text": "ML | Linear Regression" }, { "code": null, "e": 31394, "s": 31371, "text": "Reinforcement learning" }, { "code": null, "e": 31408, "s": 31394, "text": "Decision Tree" }, { "code": null, "e": 31448, "s": 31408, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31471, "s": 31448, "text": "System Design Tutorial" }, { "code": null, "e": 31515, "s": 31471, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31553, "s": 31515, "text": "Python | Decision tree implementation" }, { "code": null, "e": 31587, "s": 31553, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 31618, "s": 31587, "text": "Clustering in Machine Learning" } ]
Difference between print() and println() in Java - GeeksforGeeks
06 Apr, 2022 print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here. Various print() methods: void print(boolean b) – Prints a boolean value. void print(char c) – Prints a character. void print(char[] s) – Prints an array of characters. void print(double d) – Prints a double-precision floating-point number. void print(float f) – Prints a floating-point number. void print(int i) – Prints an integer. void print(long l) – Prints a long integer. void print(Object obj) – Prints an object. void print(String s) – Prints a string. Example: Java import java.io.*; class GFG { public static void main(String[] args) { // The cursor will remain // just after the 1 System.out.print("GfG1"); // This will be printed // just after the GfG2 System.out.print("GfG2"); }} GfG1GfG2 println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console. The next printing takes place from next line. Various println() methods: void println() – Terminates the current line by writing the line separator string. void println(boolean x) – Prints a boolean and then terminate the line. void println(char x) – Prints a character and then terminate the line. void println(char[] x) – Prints an array of characters and then terminate the line. void println(double x) – Prints a double and then terminate the line. void println(float x) – Prints a float and then terminate the line. void println(int x) – Prints an integer and then terminate the line. void println(long x) – Prints a long and then terminate the line. void println(Object x) – Prints an Object and then terminate the line. void println(String x) – Prints a String and then terminate the line. Example: Java import java.io.*; class GFG { public static void main(String[] args) { // The cursor will after GFG1 // will at the start // of the next line System.out.println("GfG1"); // This will be printed at the // start of the next line System.out.println("GfG2"); }} GfG1 GfG2 Difference between print() and println() shri14 sweetyty java-basics Java-Functions Java-I/O Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 26273, "s": 26245, "text": "\n06 Apr, 2022" }, { "code": null, "e": 26598, "s": 26273, "text": "print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here. Various print() methods:" }, { "code": null, "e": 27033, "s": 26598, "text": "void print(boolean b) – Prints a boolean value. void print(char c) – Prints a character. void print(char[] s) – Prints an array of characters. void print(double d) – Prints a double-precision floating-point number. void print(float f) – Prints a floating-point number. void print(int i) – Prints an integer. void print(long l) – Prints a long integer. void print(Object obj) – Prints an object. void print(String s) – Prints a string." }, { "code": null, "e": 27043, "s": 27033, "text": "Example: " }, { "code": null, "e": 27048, "s": 27043, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { // The cursor will remain // just after the 1 System.out.print(\"GfG1\"); // This will be printed // just after the GfG2 System.out.print(\"GfG2\"); }}", "e": 27320, "s": 27048, "text": null }, { "code": null, "e": 27329, "s": 27320, "text": "GfG1GfG2" }, { "code": null, "e": 27672, "s": 27329, "text": "println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console. The next printing takes place from next line. Various println() methods:" }, { "code": null, "e": 28396, "s": 27672, "text": "void println() – Terminates the current line by writing the line separator string. void println(boolean x) – Prints a boolean and then terminate the line. void println(char x) – Prints a character and then terminate the line. void println(char[] x) – Prints an array of characters and then terminate the line. void println(double x) – Prints a double and then terminate the line. void println(float x) – Prints a float and then terminate the line. void println(int x) – Prints an integer and then terminate the line. void println(long x) – Prints a long and then terminate the line. void println(Object x) – Prints an Object and then terminate the line. void println(String x) – Prints a String and then terminate the line." }, { "code": null, "e": 28406, "s": 28396, "text": "Example: " }, { "code": null, "e": 28411, "s": 28406, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { // The cursor will after GFG1 // will at the start // of the next line System.out.println(\"GfG1\"); // This will be printed at the // start of the next line System.out.println(\"GfG2\"); }}", "e": 28729, "s": 28411, "text": null }, { "code": null, "e": 28739, "s": 28729, "text": "GfG1\nGfG2" }, { "code": null, "e": 28780, "s": 28739, "text": "Difference between print() and println()" }, { "code": null, "e": 28787, "s": 28780, "text": "shri14" }, { "code": null, "e": 28796, "s": 28787, "text": "sweetyty" }, { "code": null, "e": 28808, "s": 28796, "text": "java-basics" }, { "code": null, "e": 28823, "s": 28808, "text": "Java-Functions" }, { "code": null, "e": 28832, "s": 28823, "text": "Java-I/O" }, { "code": null, "e": 28837, "s": 28832, "text": "Java" }, { "code": null, "e": 28856, "s": 28837, "text": "School Programming" }, { "code": null, "e": 28861, "s": 28856, "text": "Java" }, { "code": null, "e": 28959, "s": 28861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29010, "s": 28959, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29040, "s": 29010, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29059, "s": 29040, "text": "Interfaces in Java" }, { "code": null, "e": 29074, "s": 29059, "text": "Stream In Java" }, { "code": null, "e": 29105, "s": 29074, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29123, "s": 29105, "text": "Python Dictionary" }, { "code": null, "e": 29139, "s": 29123, "text": "Arrays in C/C++" }, { "code": null, "e": 29158, "s": 29139, "text": "Inheritance in C++" }, { "code": null, "e": 29182, "s": 29158, "text": "C++ Classes and Objects" } ]
Conga [Apttus Software Pvt Ltd] Interview Experience for Associate Consultant - GeeksforGeeks
26 Apr, 2021 Round 1(Aptitude): This was an aptitude test in which 20 questions were there and 60 minutes to solve it. The questions were basic aptitude questions and a few reasoning questions. Round 2(Technical): This was a technical interview. There was only one interviewer. She asked basic questions like OOPs concept, a little discussion on the project. Also, she asked me to solve two questions by writing pseudo code. One was printing pattern (pyramid numbers) and the one was to check palindrome of string and if it wasn’t string then return the reverse the string. There was only one interviewer. She asked basic questions like OOPs concept, a little discussion on the project. Also, she asked me to solve two questions by writing pseudo code. One was printing pattern (pyramid numbers) and the one was to check palindrome of string and if it wasn’t string then return the reverse the string. Round 3(Coding): It was a coding round in which I was monitored by an interviewer. You had to have your IDE set up before the round and also you cant Google. Well, you won’t need it. The question will be sent out to your account at that time only. It was of almost 90 minutes, It had four questions of which two were coding questions and two were of the database. Given an array of integers and find the closest value to the given number. The array may contain duplicate values and negative numbers.Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18] Target number: 12 Output: 11Write Block of Code to Convert String = “98989” into an integer without using any library functions.(A)Write down the query to get a record from both tables if no match found in any table then show NULL.(B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails.Normalize the given table. Given an array of integers and find the closest value to the given number. The array may contain duplicate values and negative numbers.Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18] Target number: 12 Output: 11 Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18] Target number: 12 Output: 11 Write Block of Code to Convert String = “98989” into an integer without using any library functions. (A)Write down the query to get a record from both tables if no match found in any table then show NULL.(B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails. (B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails. Normalize the given table. Round 4(Interview): It was an interview round with the senior director and manager. They asked me about myself and few coding output questions were there asked by the manager. It was a conceptual question that tests how deep you understand how everything works. Nothing to worry about if you don’t know just tell them you don’t. They asked me about myself and few coding output questions were there asked by the manager. It was a conceptual question that tests how deep you understand how everything works. Nothing to worry about if you don’t know just tell them you don’t. Conga Marketing Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus) Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
[ { "code": null, "e": 26261, "s": 26233, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26442, "s": 26261, "text": "Round 1(Aptitude): This was an aptitude test in which 20 questions were there and 60 minutes to solve it. The questions were basic aptitude questions and a few reasoning questions." }, { "code": null, "e": 26495, "s": 26442, "text": "Round 2(Technical): This was a technical interview. " }, { "code": null, "e": 26823, "s": 26495, "text": "There was only one interviewer. She asked basic questions like OOPs concept, a little discussion on the project. Also, she asked me to solve two questions by writing pseudo code. One was printing pattern (pyramid numbers) and the one was to check palindrome of string and if it wasn’t string then return the reverse the string." }, { "code": null, "e": 26937, "s": 26823, "text": "There was only one interviewer. She asked basic questions like OOPs concept, a little discussion on the project. " }, { "code": null, "e": 27152, "s": 26937, "text": "Also, she asked me to solve two questions by writing pseudo code. One was printing pattern (pyramid numbers) and the one was to check palindrome of string and if it wasn’t string then return the reverse the string." }, { "code": null, "e": 27516, "s": 27152, "text": "Round 3(Coding): It was a coding round in which I was monitored by an interviewer. You had to have your IDE set up before the round and also you cant Google. Well, you won’t need it. The question will be sent out to your account at that time only. It was of almost 90 minutes, It had four questions of which two were coding questions and two were of the database." }, { "code": null, "e": 28108, "s": 27516, "text": "Given an array of integers and find the closest value to the given number. The array may contain duplicate values and negative numbers.Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18]\nTarget number: 12\nOutput: 11Write Block of Code to Convert String = “98989” into an integer without using any library functions.(A)Write down the query to get a record from both tables if no match found in any table then show NULL.(B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails.Normalize the given table." }, { "code": null, "e": 28326, "s": 28108, "text": "Given an array of integers and find the closest value to the given number. The array may contain duplicate values and negative numbers.Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18]\nTarget number: 12\nOutput: 11" }, { "code": null, "e": 28409, "s": 28326, "text": "Example : Array : = [2,5,6,7,8,8,9,11,22,19,14,15,18]\nTarget number: 12\nOutput: 11" }, { "code": null, "e": 28510, "s": 28409, "text": "Write Block of Code to Convert String = “98989” into an integer without using any library functions." }, { "code": null, "e": 28759, "s": 28510, "text": "(A)Write down the query to get a record from both tables if no match found in any table then show NULL.(B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails." }, { "code": null, "e": 28905, "s": 28759, "text": "(B)Write down the query to fetch empname even they have not matched any id in the left table, Order by firstname from empdetails and projdetails." }, { "code": null, "e": 28932, "s": 28905, "text": "Normalize the given table." }, { "code": null, "e": 29017, "s": 28932, "text": "Round 4(Interview): It was an interview round with the senior director and manager. " }, { "code": null, "e": 29262, "s": 29017, "text": "They asked me about myself and few coding output questions were there asked by the manager. It was a conceptual question that tests how deep you understand how everything works. Nothing to worry about if you don’t know just tell them you don’t." }, { "code": null, "e": 29355, "s": 29262, "text": "They asked me about myself and few coding output questions were there asked by the manager. " }, { "code": null, "e": 29508, "s": 29355, "text": "It was a conceptual question that tests how deep you understand how everything works. Nothing to worry about if you don’t know just tell them you don’t." }, { "code": null, "e": 29514, "s": 29508, "text": "Conga" }, { "code": null, "e": 29524, "s": 29514, "text": "Marketing" }, { "code": null, "e": 29546, "s": 29524, "text": "Interview Experiences" }, { "code": null, "e": 29644, "s": 29546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29695, "s": 29644, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 29737, "s": 29695, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 29793, "s": 29737, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 29821, "s": 29793, "text": "Amazon Interview Experience" }, { "code": null, "e": 29859, "s": 29821, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29898, "s": 29859, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 29944, "s": 29898, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 30016, "s": 29944, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 30066, "s": 30016, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
Longest sequence of positive integers in an array - GeeksforGeeks
21 May, 2021 Find the longest running positive sequence in an array.Examples: Input : arr[] = {1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6} Output :Index : 7, length : 5 Input : arr[] = {-3, -6, -1, -3, -8} Output : No positive sequence detected. A simple solution is to use two nested loops. In the outer loop, we look for positive elements. In the inner loop, we count number of positives starting with the positive element picked by outer loop. Time complexity of this solution is O(n^2).An efficient solution is to use one single loop. We keep incrementing count while we see positive integers. We reset count to 0 after seeing a negative. Before resetting, we check if count is more than maximum. C++ Java Python3 C# PHP Javascript // CPP program to find longest running sequence// of positive integers.#include <bits/stdc++.h>using namespace std; // Prints longest sequence of positive integers in// an array.void getLongestSeq(int a[], int n){ // Variables to keep track of maximum length and // starting point of maximum length. And same // for current length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) cout << "Length " << maxLen << ", starting index " << maxIdx << endl; else cout << "No positive sequence detected." << endl; return;} // Driver codeint main(){ int arr[] = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = sizeof(arr) / sizeof(int); getLongestSeq(arr, n); return 0;} // Java program to find longest running// sequence of positive integersimport java.io.*; class GFG { // Prints longest sequence of // positive integers in an array. static void getLongestSeq(int a[], int n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { System.out.print( "Length " + maxLen) ; System.out.print( ",starting index " + maxIdx ); } else System.out.println("No positive sequence detected.") ; return; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = arr.length; getLongestSeq(arr, n); }} // This article is contributed by vt_m. # Python code to find longest running# sequence of positive integers. def getLongestSeq(a, n): maxIdx = 0 maxLen = 0 currLen = 0 currIdx = 0 for k in range(n): if a[k] > 0: currLen +=1 # New sequence, store # beginning index. if currLen == 1: currIdx = k else: if currLen > maxLen: maxLen = currLen maxIdx = currIdx currLen = 0 if maxLen > 0: print('Index : ',maxIdx,',Length : ',maxLen,) else: print("No positive sequence detected.") # Driver codearr = [ 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6]n = len(arr)getLongestSeq(arr, n) # This code is contributed by "Abhishek Sharma 44" // C# program to find longest running// sequence of positive integers.using System; class GFG { // Prints longest sequence of // positive integers in an array. static void getLongestSeq(int []a, int n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { Console.Write( "Length " + maxLen) ; Console.WriteLine( ",starting index " + maxIdx ); } else Console.WriteLine("No positive sequence" + " detected.") ; return; } // driver code public static void Main() { int []arr = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = arr.Length; getLongestSeq(arr, n); } }// This code is contributed by Sam007 <?php// PHP program to find longest running// sequence of positive integers. // Prints longest sequence of positive// integers in an array.function getLongestSeq($a, $n){ // Variables to keep track // of maximum length and // starting point of maximum // length. And same for // current length. $maxIdx = 0; $maxLen = 0; $currLen = 0; $currIdx = 0; for ($k = 0; $k < $n; $k++) { if ($a[$k] > 0) { $currLen++; // New sequence, store // beginning index. if ($currLen == 1) $currIdx = $k; } else { if ($currLen > $maxLen) { $maxLen = $currLen; $maxIdx = $currIdx; } $currLen = 0; } } if ($maxLen > 0) echo "Length " . $maxLen. ", starting index " . $maxIdx ."\n" ; else echo "No positive sequence detected."."\n"; return;} // Driver Code $arr = array(1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6); $n = count($arr); getLongestSeq($arr, $n); // This code is contributed by Sam007?> <script> // Javascript program to find longest running // sequence of positive integers. // Prints longest sequence of // positive integers in an array. function getLongestSeq(a, n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. let maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (let k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { document.write( "Length " + maxLen) ; document.write( ", starting index " + maxIdx + "</br>"); } else document.write("No positive sequence" + " detected.") ; return; } let arr = [ 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 ]; let n = arr.length; getLongestSeq(arr, n); </script> Output: Length 5, starting index 7 The algorithm is O(n) time and O(1) auxiliary space. Sam007 divyesh072019 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Remove duplicates from sorted array Find subarray with given sum | Set 1 (Nonnegative Numbers) Move all negative numbers to beginning and positive to end with constant extra space Building Heap from Array
[ { "code": null, "e": 26067, "s": 26039, "text": "\n21 May, 2021" }, { "code": null, "e": 26134, "s": 26067, "text": "Find the longest running positive sequence in an array.Examples: " }, { "code": null, "e": 26329, "s": 26134, "text": "Input : arr[] = {1, 2, -3, 2, 3, 4, -6, 1, \n 2, 3, 4, 5, -8, 5, 6}\nOutput :Index : 7, length : 5\n\nInput : arr[] = {-3, -6, -1, -3, -8}\nOutput : No positive sequence detected." }, { "code": null, "e": 26787, "s": 26331, "text": "A simple solution is to use two nested loops. In the outer loop, we look for positive elements. In the inner loop, we count number of positives starting with the positive element picked by outer loop. Time complexity of this solution is O(n^2).An efficient solution is to use one single loop. We keep incrementing count while we see positive integers. We reset count to 0 after seeing a negative. Before resetting, we check if count is more than maximum. " }, { "code": null, "e": 26791, "s": 26787, "text": "C++" }, { "code": null, "e": 26796, "s": 26791, "text": "Java" }, { "code": null, "e": 26804, "s": 26796, "text": "Python3" }, { "code": null, "e": 26807, "s": 26804, "text": "C#" }, { "code": null, "e": 26811, "s": 26807, "text": "PHP" }, { "code": null, "e": 26822, "s": 26811, "text": "Javascript" }, { "code": "// CPP program to find longest running sequence// of positive integers.#include <bits/stdc++.h>using namespace std; // Prints longest sequence of positive integers in// an array.void getLongestSeq(int a[], int n){ // Variables to keep track of maximum length and // starting point of maximum length. And same // for current length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) cout << \"Length \" << maxLen << \", starting index \" << maxIdx << endl; else cout << \"No positive sequence detected.\" << endl; return;} // Driver codeint main(){ int arr[] = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = sizeof(arr) / sizeof(int); getLongestSeq(arr, n); return 0;}", "e": 27988, "s": 26822, "text": null }, { "code": "// Java program to find longest running// sequence of positive integersimport java.io.*; class GFG { // Prints longest sequence of // positive integers in an array. static void getLongestSeq(int a[], int n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { System.out.print( \"Length \" + maxLen) ; System.out.print( \",starting index \" + maxIdx ); } else System.out.println(\"No positive sequence detected.\") ; return; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = arr.length; getLongestSeq(arr, n); }} // This article is contributed by vt_m.", "e": 29461, "s": 27988, "text": null }, { "code": "# Python code to find longest running# sequence of positive integers. def getLongestSeq(a, n): maxIdx = 0 maxLen = 0 currLen = 0 currIdx = 0 for k in range(n): if a[k] > 0: currLen +=1 # New sequence, store # beginning index. if currLen == 1: currIdx = k else: if currLen > maxLen: maxLen = currLen maxIdx = currIdx currLen = 0 if maxLen > 0: print('Index : ',maxIdx,',Length : ',maxLen,) else: print(\"No positive sequence detected.\") # Driver codearr = [ 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6]n = len(arr)getLongestSeq(arr, n) # This code is contributed by \"Abhishek Sharma 44\"", "e": 30230, "s": 29461, "text": null }, { "code": "// C# program to find longest running// sequence of positive integers.using System; class GFG { // Prints longest sequence of // positive integers in an array. static void getLongestSeq(int []a, int n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. int maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (int k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { Console.Write( \"Length \" + maxLen) ; Console.WriteLine( \",starting index \" + maxIdx ); } else Console.WriteLine(\"No positive sequence\" + \" detected.\") ; return; } // driver code public static void Main() { int []arr = { 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 }; int n = arr.Length; getLongestSeq(arr, n); } }// This code is contributed by Sam007", "e": 31776, "s": 30230, "text": null }, { "code": "<?php// PHP program to find longest running// sequence of positive integers. // Prints longest sequence of positive// integers in an array.function getLongestSeq($a, $n){ // Variables to keep track // of maximum length and // starting point of maximum // length. And same for // current length. $maxIdx = 0; $maxLen = 0; $currLen = 0; $currIdx = 0; for ($k = 0; $k < $n; $k++) { if ($a[$k] > 0) { $currLen++; // New sequence, store // beginning index. if ($currLen == 1) $currIdx = $k; } else { if ($currLen > $maxLen) { $maxLen = $currLen; $maxIdx = $currIdx; } $currLen = 0; } } if ($maxLen > 0) echo \"Length \" . $maxLen. \", starting index \" . $maxIdx .\"\\n\" ; else echo \"No positive sequence detected.\".\"\\n\"; return;} // Driver Code $arr = array(1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6); $n = count($arr); getLongestSeq($arr, $n); // This code is contributed by Sam007?>", "e": 32940, "s": 31776, "text": null }, { "code": "<script> // Javascript program to find longest running // sequence of positive integers. // Prints longest sequence of // positive integers in an array. function getLongestSeq(a, n) { // Variables to keep track of maximum // length and starting point of // maximum length. And same for current // length. let maxIdx = 0, maxLen = 0, currLen = 0, currIdx = 0; for (let k = 0; k < n; k++) { if (a[k] > 0) { currLen++; // New sequence, store // beginning index. if (currLen == 1) currIdx = k; } else { if (currLen > maxLen) { maxLen = currLen; maxIdx = currIdx; } currLen = 0; } } if (maxLen > 0) { document.write( \"Length \" + maxLen) ; document.write( \", starting index \" + maxIdx + \"</br>\"); } else document.write(\"No positive sequence\" + \" detected.\") ; return; } let arr = [ 1, 2, -3, 2, 3, 4, -6, 1, 2, 3, 4, 5, -8, 5, 6 ]; let n = arr.length; getLongestSeq(arr, n); </script>", "e": 34374, "s": 32940, "text": null }, { "code": null, "e": 34384, "s": 34374, "text": "Output: " }, { "code": null, "e": 34411, "s": 34384, "text": "Length 5, starting index 7" }, { "code": null, "e": 34465, "s": 34411, "text": "The algorithm is O(n) time and O(1) auxiliary space. " }, { "code": null, "e": 34472, "s": 34465, "text": "Sam007" }, { "code": null, "e": 34486, "s": 34472, "text": "divyesh072019" }, { "code": null, "e": 34493, "s": 34486, "text": "Arrays" }, { "code": null, "e": 34500, "s": 34493, "text": "Arrays" }, { "code": null, "e": 34598, "s": 34500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34625, "s": 34598, "text": "Count pairs with given sum" }, { "code": null, "e": 34656, "s": 34625, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34681, "s": 34656, "text": "Window Sliding Technique" }, { "code": null, "e": 34719, "s": 34681, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34740, "s": 34719, "text": "Next Greater Element" }, { "code": null, "e": 34798, "s": 34740, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 34834, "s": 34798, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 34893, "s": 34834, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 34978, "s": 34893, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
How to get the elements of one array which are not present in another array using JavaScript? - GeeksforGeeks
12 Sep, 2019 The task is to get the elements of the one array which are not present in the another array. Here we are going to use JavaScript to achieve the goal. Here are few techniques discussed.Approach Take the arrays in variables. Use the .filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output. Example 1: This example using the approach discussed above. <!DOCTYPE HTML><html> <head> <title> How to get the elements of one array which are not present in another array using JavaScript? </title></head> <body style="text-align:center;" id="body"> <h1 id="h1" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var ar1 = [1, 2, 3, 4]; var ar2 = [2, 4]; el_up.innerHTML = "Click on the button to remove the element of "+ "second from the first array.<br><br> firstArray - " + ar1 + "<br>secondArray - " + ar2; function gfg_Run() { var elmts = ar1.filter( function(i) { return this.indexOf(i) < 0; }, ar2 ); el_down.innerHTML = elmts; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example using the same approach but different methods of javaScript. <!DOCTYPE HTML><html> <head> <title> How to get the elements of one array which are not present in another array using JavaScript? </title></head> <body style="text-align:center;" id="body"> <h1 id="h1" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var ar1 = [1, 2, 3, 4]; var ar2 = [2, 4]; el_up.innerHTML = "Click on the button to remove the element of second"+ " from the first array.<br><br> firstArray - " + ar1 + "<br>secondArray - " + ar2; function gfg_Run() { var elmts = ar1.filter(f => !ar2.includes(f)); el_down.innerHTML = elmts; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n12 Sep, 2019" }, { "code": null, "e": 26738, "s": 26545, "text": "The task is to get the elements of the one array which are not present in the another array. Here we are going to use JavaScript to achieve the goal. Here are few techniques discussed.Approach" }, { "code": null, "e": 26768, "s": 26738, "text": "Take the arrays in variables." }, { "code": null, "e": 26928, "s": 26768, "text": "Use the .filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output." }, { "code": null, "e": 26988, "s": 26928, "text": "Example 1: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the elements of one array which are not present in another array using JavaScript? </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 id=\"h1\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var ar1 = [1, 2, 3, 4]; var ar2 = [2, 4]; el_up.innerHTML = \"Click on the button to remove the element of \"+ \"second from the first array.<br><br> firstArray - \" + ar1 + \"<br>secondArray - \" + ar2; function gfg_Run() { var elmts = ar1.filter( function(i) { return this.indexOf(i) < 0; }, ar2 ); el_down.innerHTML = elmts; } </script></body> </html>", "e": 28195, "s": 26988, "text": null }, { "code": null, "e": 28203, "s": 28195, "text": "Output:" }, { "code": null, "e": 28234, "s": 28203, "text": "Before clicking on the button:" }, { "code": null, "e": 28264, "s": 28234, "text": "After clicking on the button:" }, { "code": null, "e": 28349, "s": 28264, "text": "Example 2: This example using the same approach but different methods of javaScript." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the elements of one array which are not present in another array using JavaScript? </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 id=\"h1\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var ar1 = [1, 2, 3, 4]; var ar2 = [2, 4]; el_up.innerHTML = \"Click on the button to remove the element of second\"+ \" from the first array.<br><br> firstArray - \" + ar1 + \"<br>secondArray - \" + ar2; function gfg_Run() { var elmts = ar1.filter(f => !ar2.includes(f)); el_down.innerHTML = elmts; } </script></body> </html>", "e": 29429, "s": 28349, "text": null }, { "code": null, "e": 29437, "s": 29429, "text": "Output:" }, { "code": null, "e": 29468, "s": 29437, "text": "Before clicking on the button:" }, { "code": null, "e": 29498, "s": 29468, "text": "After clicking on the button:" }, { "code": null, "e": 29514, "s": 29498, "text": "JavaScript-Misc" }, { "code": null, "e": 29525, "s": 29514, "text": "JavaScript" }, { "code": null, "e": 29542, "s": 29525, "text": "Web Technologies" }, { "code": null, "e": 29569, "s": 29542, "text": "Web technologies Questions" }, { "code": null, "e": 29667, "s": 29569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29707, "s": 29667, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29768, "s": 29707, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29809, "s": 29768, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29831, "s": 29809, "text": "JavaScript | Promises" }, { "code": null, "e": 29885, "s": 29831, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29925, "s": 29885, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29958, "s": 29925, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30001, "s": 29958, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30051, "s": 30001, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Output of Python Program - Dictionary (set 25) - GeeksforGeeks
14 Oct, 2020 Prerequisite: Dictionaries in PythonThese question sets will make you conversant with Dictionary Concepts in Python programming language. Question 1: Which of the following is true about Python dictionaries? A. Items are accessed by their position in a dictionary. B. All the keys in a dictionary must be of the same type. C. Dictionaries are mutable. D. A dictionary can contain any object type except another dictionary. Answer: B Explanation: It means that you can change their content without changing their identity. Question 2: Suppose we have a dictionary defined as : Python3 Python = {'Geeks': 100, 'For': 200, 'Geeks': 300}Python ['For':'Geeks'] What is the result of this statement: Python3 Python ['For':'Geeks'] A. [200, 300] B. (200, 300) C. It raises an exception. D. 200 300 Answer: C Explanation: Dictionaries are accessed by key, not by the position of the items. It doesn’t make sense to slice a dictionary. Question 3: Which of the following could not be a valid dictionary key: A. len B. (5+7j) C. (‘Geeks’,’For’) D. [‘Geeks’,’For’] Answer: D Explanation: A list is a mutable data structure so it cannot be used as a key as it raises the risk of modification and thus, aren’t hashable. Question 4. Suppose you have the following dictionary defined as- Python3 Python = {'Geeks': 100, 'For': 200, 'Geeks': 300} What method call will delete the entry whose value is 100? A. push() B. pop() C. append() D. extend() Answer: B Explanation: The pop() is an inbuilt function in Python that removes the item from the dictionary provided the key as a parameter. Question 5. Suppose you have a dictionary d1. Which of the following effectively creates a variable d2 which contains a copy of d1? A. d2 = dict(d1.keys()) B. d2 = dict(d1.values()) C. d2 = d1 D. d2 = dict(d1.items()) Answer: D Explanation: The d1 dictionary can be passed directly as an argument to dict() to create a new dictionary. Question 6. What will be the output of the following code snippet? Python3 y={16:"Geeks",25:"For",32:"Geeks"} for i,j in y.items(): print(i,j,end=" ") A. Geeks For Geeks B. 16 Geeks 25 For 32 Geeks C. 16 25 32 D. 16 :”Geeks” 25:”For” 32:”Geeks” Answer: B Explanation: Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter. Question 7. What is the correct command to shuffle the following list? Python3 d = {"Albert":70, "Suzan":85}d["Albert"] A. 85 B. “Albert” C. 70 D. “Suzan” Answer: C Explanation: A key can be used to access the value in a dictionary. Question 8. Which statement defined below can create a dictionary? A. d = {“Computer”:100, “Programming”:95} B. d = {100:” Computer”, 95:”Programming”} C. d = { } D. All the above. Answer: D Explanation: Since there are multiple methods to define dictionary ,all of which are defined above. Question 9. Which of the following statements can be used for declaration of the dictionary? A. {23: ‘Geeks’, 26: ‘ForGeeks’} B. dict([[23,”Geeks”],[26,”ForGeeks”]]) C. {23,”Geeks”,26”ForGeeks”} D. All the above Answer: A Explanation: Because a dictionary has a key and a value which should be defined as {key: value} Question10. Let us assume d = {“Nobita”:70, “Doremon”:65} . Which command you will use to delete the entry for “Nobita”: A. d.delete(“Nobita”:70) B. d.delete(“Nobita”) C. del d[“Nobita”] D. del d(“Nobita”:70) Answer: C Explanation: The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc. MCQ Python Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python-Quizzes | Python List Quiz | Question 4 Python-Quizzes | Python Dictionary Quiz | Question 25 Python-Quizzes | Python List Quiz | Question 5 Python-Quizzes | Python Dictionary Quiz | Question 23 Python | Miscellaneous | Question 1
[ { "code": null, "e": 25579, "s": 25551, "text": "\n14 Oct, 2020" }, { "code": null, "e": 25717, "s": 25579, "text": "Prerequisite: Dictionaries in PythonThese question sets will make you conversant with Dictionary Concepts in Python programming language." }, { "code": null, "e": 25787, "s": 25717, "text": "Question 1: Which of the following is true about Python dictionaries?" }, { "code": null, "e": 25844, "s": 25787, "text": "A. Items are accessed by their position in a dictionary." }, { "code": null, "e": 25902, "s": 25844, "text": "B. All the keys in a dictionary must be of the same type." }, { "code": null, "e": 25931, "s": 25902, "text": "C. Dictionaries are mutable." }, { "code": null, "e": 26002, "s": 25931, "text": "D. A dictionary can contain any object type except another dictionary." }, { "code": null, "e": 26012, "s": 26002, "text": "Answer: B" }, { "code": null, "e": 26101, "s": 26012, "text": "Explanation: It means that you can change their content without changing their identity." }, { "code": null, "e": 26155, "s": 26101, "text": "Question 2: Suppose we have a dictionary defined as :" }, { "code": null, "e": 26163, "s": 26155, "text": "Python3" }, { "code": "Python = {'Geeks': 100, 'For': 200, 'Geeks': 300}Python ['For':'Geeks']", "e": 26235, "s": 26163, "text": null }, { "code": null, "e": 26273, "s": 26235, "text": "What is the result of this statement:" }, { "code": null, "e": 26281, "s": 26273, "text": "Python3" }, { "code": "Python ['For':'Geeks']", "e": 26304, "s": 26281, "text": null }, { "code": null, "e": 26318, "s": 26304, "text": "A. [200, 300]" }, { "code": null, "e": 26332, "s": 26318, "text": "B. (200, 300)" }, { "code": null, "e": 26359, "s": 26332, "text": "C. It raises an exception." }, { "code": null, "e": 26370, "s": 26359, "text": "D. 200 300" }, { "code": null, "e": 26380, "s": 26370, "text": "Answer: C" }, { "code": null, "e": 26506, "s": 26380, "text": "Explanation: Dictionaries are accessed by key, not by the position of the items. It doesn’t make sense to slice a dictionary." }, { "code": null, "e": 26578, "s": 26506, "text": "Question 3: Which of the following could not be a valid dictionary key:" }, { "code": null, "e": 26585, "s": 26578, "text": "A. len" }, { "code": null, "e": 26595, "s": 26585, "text": "B. (5+7j)" }, { "code": null, "e": 26614, "s": 26595, "text": "C. (‘Geeks’,’For’)" }, { "code": null, "e": 26633, "s": 26614, "text": "D. [‘Geeks’,’For’]" }, { "code": null, "e": 26643, "s": 26633, "text": "Answer: D" }, { "code": null, "e": 26786, "s": 26643, "text": "Explanation: A list is a mutable data structure so it cannot be used as a key as it raises the risk of modification and thus, aren’t hashable." }, { "code": null, "e": 26853, "s": 26786, "text": "Question 4. Suppose you have the following dictionary defined as- " }, { "code": null, "e": 26861, "s": 26853, "text": "Python3" }, { "code": "Python = {'Geeks': 100, 'For': 200, 'Geeks': 300}", "e": 26911, "s": 26861, "text": null }, { "code": null, "e": 26970, "s": 26911, "text": "What method call will delete the entry whose value is 100?" }, { "code": null, "e": 26980, "s": 26970, "text": "A. push()" }, { "code": null, "e": 26989, "s": 26980, "text": "B. pop()" }, { "code": null, "e": 27001, "s": 26989, "text": "C. append()" }, { "code": null, "e": 27013, "s": 27001, "text": "D. extend()" }, { "code": null, "e": 27023, "s": 27013, "text": "Answer: B" }, { "code": null, "e": 27154, "s": 27023, "text": "Explanation: The pop() is an inbuilt function in Python that removes the item from the dictionary provided the key as a parameter." }, { "code": null, "e": 27286, "s": 27154, "text": "Question 5. Suppose you have a dictionary d1. Which of the following effectively creates a variable d2 which contains a copy of d1?" }, { "code": null, "e": 27310, "s": 27286, "text": "A. d2 = dict(d1.keys())" }, { "code": null, "e": 27336, "s": 27310, "text": "B. d2 = dict(d1.values())" }, { "code": null, "e": 27347, "s": 27336, "text": "C. d2 = d1" }, { "code": null, "e": 27372, "s": 27347, "text": "D. d2 = dict(d1.items())" }, { "code": null, "e": 27382, "s": 27372, "text": "Answer: D" }, { "code": null, "e": 27489, "s": 27382, "text": "Explanation: The d1 dictionary can be passed directly as an argument to dict() to create a new dictionary." }, { "code": null, "e": 27556, "s": 27489, "text": "Question 6. What will be the output of the following code snippet?" }, { "code": null, "e": 27564, "s": 27556, "text": "Python3" }, { "code": "y={16:\"Geeks\",25:\"For\",32:\"Geeks\"} for i,j in y.items(): print(i,j,end=\" \")", "e": 27644, "s": 27564, "text": null }, { "code": null, "e": 27663, "s": 27644, "text": "A. Geeks For Geeks" }, { "code": null, "e": 27692, "s": 27663, "text": "B. 16 Geeks 25 For 32 Geeks" }, { "code": null, "e": 27704, "s": 27692, "text": "C. 16 25 32" }, { "code": null, "e": 27739, "s": 27704, "text": "D. 16 :”Geeks” 25:”For” 32:”Geeks”" }, { "code": null, "e": 27749, "s": 27739, "text": "Answer: B" }, { "code": null, "e": 27981, "s": 27749, "text": "Explanation: Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter." }, { "code": null, "e": 28052, "s": 27981, "text": "Question 7. What is the correct command to shuffle the following list?" }, { "code": null, "e": 28060, "s": 28052, "text": "Python3" }, { "code": "d = {\"Albert\":70, \"Suzan\":85}d[\"Albert\"]", "e": 28101, "s": 28060, "text": null }, { "code": null, "e": 28107, "s": 28101, "text": "A. 85" }, { "code": null, "e": 28119, "s": 28107, "text": "B. “Albert”" }, { "code": null, "e": 28125, "s": 28119, "text": "C. 70" }, { "code": null, "e": 28136, "s": 28125, "text": "D. “Suzan”" }, { "code": null, "e": 28146, "s": 28136, "text": "Answer: C" }, { "code": null, "e": 28214, "s": 28146, "text": "Explanation: A key can be used to access the value in a dictionary." }, { "code": null, "e": 28281, "s": 28214, "text": "Question 8. Which statement defined below can create a dictionary?" }, { "code": null, "e": 28323, "s": 28281, "text": "A. d = {“Computer”:100, “Programming”:95}" }, { "code": null, "e": 28366, "s": 28323, "text": "B. d = {100:” Computer”, 95:”Programming”}" }, { "code": null, "e": 28377, "s": 28366, "text": "C. d = { }" }, { "code": null, "e": 28395, "s": 28377, "text": "D. All the above." }, { "code": null, "e": 28405, "s": 28395, "text": "Answer: D" }, { "code": null, "e": 28505, "s": 28405, "text": "Explanation: Since there are multiple methods to define dictionary ,all of which are defined above." }, { "code": null, "e": 28598, "s": 28505, "text": "Question 9. Which of the following statements can be used for declaration of the dictionary?" }, { "code": null, "e": 28631, "s": 28598, "text": "A. {23: ‘Geeks’, 26: ‘ForGeeks’}" }, { "code": null, "e": 28671, "s": 28631, "text": "B. dict([[23,”Geeks”],[26,”ForGeeks”]])" }, { "code": null, "e": 28700, "s": 28671, "text": "C. {23,”Geeks”,26”ForGeeks”}" }, { "code": null, "e": 28717, "s": 28700, "text": "D. All the above" }, { "code": null, "e": 28727, "s": 28717, "text": "Answer: A" }, { "code": null, "e": 28823, "s": 28727, "text": "Explanation: Because a dictionary has a key and a value which should be defined as {key: value}" }, { "code": null, "e": 28945, "s": 28823, "text": "Question10. Let us assume d = {“Nobita”:70, “Doremon”:65} . Which command you will use to delete the entry for “Nobita”:" }, { "code": null, "e": 28970, "s": 28945, "text": "A. d.delete(“Nobita”:70)" }, { "code": null, "e": 28992, "s": 28970, "text": "B. d.delete(“Nobita”)" }, { "code": null, "e": 29011, "s": 28992, "text": "C. del d[“Nobita”]" }, { "code": null, "e": 29033, "s": 29011, "text": "D. del d(“Nobita”:70)" }, { "code": null, "e": 29043, "s": 29033, "text": "Answer: C" }, { "code": null, "e": 29222, "s": 29043, "text": "Explanation: The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc." }, { "code": null, "e": 29226, "s": 29222, "text": "MCQ" }, { "code": null, "e": 29233, "s": 29226, "text": "Python" }, { "code": null, "e": 29248, "s": 29233, "text": "Python-Quizzes" }, { "code": null, "e": 29346, "s": 29248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29378, "s": 29346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29420, "s": 29378, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29462, "s": 29420, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29518, "s": 29462, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29545, "s": 29518, "text": "Python Classes and Objects" }, { "code": null, "e": 29592, "s": 29545, "text": "Python-Quizzes | Python List Quiz | Question 4" }, { "code": null, "e": 29646, "s": 29592, "text": "Python-Quizzes | Python Dictionary Quiz | Question 25" }, { "code": null, "e": 29693, "s": 29646, "text": "Python-Quizzes | Python List Quiz | Question 5" }, { "code": null, "e": 29747, "s": 29693, "text": "Python-Quizzes | Python Dictionary Quiz | Question 23" } ]
How to use loading animation by using the react-loader-spinner through npm ? - GeeksforGeeks
03 Sep, 2021 The spinner to indicate the loading state. We can also modify the appearance, size, and placement of the spinners with the propeTypes available in the react-loader-spinner. The react-loader-spinner is an npm package that provides a simple and attractive SVG spinner component that can be used in any of your projects. This package has more than 75k+ downloads weekly. Here for loader, we are going to use npm package called react-loader-spinner. It is a package for loaders. For in-depth knowledge, you can visit the below link. https://www.npmjs.com/package/react-loader-spinner Syntax: <Loader type="Spinner Type" color="rgb color" height={number} width={number} timeout={number in ms} />; Types of spinner: All types of the spinner can be used similarly you just need to change the type of the loader. Audio Ball-Triangle Bars Circles Grid Hearts Oval Puff Rings TailSpin ThreeDots PropTypes: All the types of spinner accept these props. visible: It is a boolean value that defines that the spinner should be visible or not, the default value is false. type: This prop defines the spinner type. height: This prop defines the height of the SVG spinner and the default value is 80. width: This prop defines the width of the SVG spinner and the default value is 80. color: This prop defines the color of the spinner. secondaryColor: This prop is available on the plane and mutatingDots loaders. timeout: This defines the effective time of the spinner. radius: This prop set the radius of the spinner. Creating React Application and Installing Module: Step 1: Create the React app using the command. npx create-react-app foldername Step 2: Now move into your project folder i.e. foldername by using this command. cd foldername Step 3: Now install the package into your project folder. npm install react-loader-spinner Step 4: Now create a new file into your src folder i.e. loader.js Project Structure: It will look like this. Here our folder name is react_loader. Example: In this example, we will create a loading spinner, for that, we have already created a component file that is loader.js. We will call the loadr.js file into our main rendering file App.js Output: Reference: https://www.npmjs.com/package/react-loader-spinner rs1686740 React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook How to set background images in ReactJS ? Re-rendering Components in ReactJS Axios in React: A Guide for Beginners Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26304, "s": 26276, "text": "\n03 Sep, 2021" }, { "code": null, "e": 26672, "s": 26304, "text": "The spinner to indicate the loading state. We can also modify the appearance, size, and placement of the spinners with the propeTypes available in the react-loader-spinner. The react-loader-spinner is an npm package that provides a simple and attractive SVG spinner component that can be used in any of your projects. This package has more than 75k+ downloads weekly." }, { "code": null, "e": 26833, "s": 26672, "text": "Here for loader, we are going to use npm package called react-loader-spinner. It is a package for loaders. For in-depth knowledge, you can visit the below link." }, { "code": null, "e": 26884, "s": 26833, "text": "https://www.npmjs.com/package/react-loader-spinner" }, { "code": null, "e": 26892, "s": 26884, "text": "Syntax:" }, { "code": null, "e": 27006, "s": 26892, "text": "<Loader\n type=\"Spinner Type\"\n color=\"rgb color\"\n height={number}\n width={number}\n timeout={number in ms}\n/>;" }, { "code": null, "e": 27119, "s": 27006, "text": "Types of spinner: All types of the spinner can be used similarly you just need to change the type of the loader." }, { "code": null, "e": 27125, "s": 27119, "text": "Audio" }, { "code": null, "e": 27139, "s": 27125, "text": "Ball-Triangle" }, { "code": null, "e": 27144, "s": 27139, "text": "Bars" }, { "code": null, "e": 27152, "s": 27144, "text": "Circles" }, { "code": null, "e": 27157, "s": 27152, "text": "Grid" }, { "code": null, "e": 27164, "s": 27157, "text": "Hearts" }, { "code": null, "e": 27169, "s": 27164, "text": "Oval" }, { "code": null, "e": 27174, "s": 27169, "text": "Puff" }, { "code": null, "e": 27180, "s": 27174, "text": "Rings" }, { "code": null, "e": 27189, "s": 27180, "text": "TailSpin" }, { "code": null, "e": 27199, "s": 27189, "text": "ThreeDots" }, { "code": null, "e": 27255, "s": 27199, "text": "PropTypes: All the types of spinner accept these props." }, { "code": null, "e": 27370, "s": 27255, "text": "visible: It is a boolean value that defines that the spinner should be visible or not, the default value is false." }, { "code": null, "e": 27412, "s": 27370, "text": "type: This prop defines the spinner type." }, { "code": null, "e": 27497, "s": 27412, "text": "height: This prop defines the height of the SVG spinner and the default value is 80." }, { "code": null, "e": 27580, "s": 27497, "text": "width: This prop defines the width of the SVG spinner and the default value is 80." }, { "code": null, "e": 27631, "s": 27580, "text": "color: This prop defines the color of the spinner." }, { "code": null, "e": 27709, "s": 27631, "text": "secondaryColor: This prop is available on the plane and mutatingDots loaders." }, { "code": null, "e": 27766, "s": 27709, "text": "timeout: This defines the effective time of the spinner." }, { "code": null, "e": 27815, "s": 27766, "text": "radius: This prop set the radius of the spinner." }, { "code": null, "e": 27865, "s": 27815, "text": "Creating React Application and Installing Module:" }, { "code": null, "e": 27913, "s": 27865, "text": "Step 1: Create the React app using the command." }, { "code": null, "e": 27948, "s": 27915, "text": "npx create-react-app foldername " }, { "code": null, "e": 28029, "s": 27948, "text": "Step 2: Now move into your project folder i.e. foldername by using this command." }, { "code": null, "e": 28045, "s": 28031, "text": "cd foldername" }, { "code": null, "e": 28103, "s": 28045, "text": "Step 3: Now install the package into your project folder." }, { "code": null, "e": 28138, "s": 28105, "text": "npm install react-loader-spinner" }, { "code": null, "e": 28204, "s": 28138, "text": "Step 4: Now create a new file into your src folder i.e. loader.js" }, { "code": null, "e": 28285, "s": 28204, "text": "Project Structure: It will look like this. Here our folder name is react_loader." }, { "code": null, "e": 28482, "s": 28285, "text": "Example: In this example, we will create a loading spinner, for that, we have already created a component file that is loader.js. We will call the loadr.js file into our main rendering file App.js" }, { "code": null, "e": 28498, "s": 28490, "text": "Output:" }, { "code": null, "e": 28564, "s": 28502, "text": "Reference: https://www.npmjs.com/package/react-loader-spinner" }, { "code": null, "e": 28576, "s": 28566, "text": "rs1686740" }, { "code": null, "e": 28592, "s": 28576, "text": "React-Questions" }, { "code": null, "e": 28600, "s": 28592, "text": "ReactJS" }, { "code": null, "e": 28617, "s": 28600, "text": "Web Technologies" }, { "code": null, "e": 28715, "s": 28617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28783, "s": 28715, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 28810, "s": 28783, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28852, "s": 28810, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28887, "s": 28852, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 28925, "s": 28887, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28965, "s": 28925, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28998, "s": 28965, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29043, "s": 28998, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29105, "s": 29043, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
p5.js | doubleClicked() Function - GeeksforGeeks
17 Jan, 2020 The doubleClicked() function is invoked whenever a mouse or pointing device causes a dblclick event. This happens when the pointing device is clicked twice in quick succession on a single element. The MouseEvent callback argument could be used to access the details of the click. Syntax: doubleClicked([event]) Parameters: This function accepts a single parameter as mentioned above and described below: event: This is an optional MouseEvent callback argument. It can be used to access the click details. The program below illustrate the doubleClicked() function in p5.js: Example 1: Using double click to change the fill color. let colorVal = 0; function setup() { createCanvas(500, 300); textSize(24);} function draw() { clear(); // apply fill based on the red component fill(colorVal, 128, 255 - colorVal) text("Double click to change the color", 20, 20); circle(150, 150, 200);} function doubleClicked() { // change the value if // the event occurs if (colorVal < 255) colorVal += 50; else colorVal = 0;} Output:Example 2: Accessing the details of the MouseEvent object. let y = 60; function setup() { createCanvas(500, 200); textSize(16); text("Double click the mouse to see doubleClicked() function fire", 10, 20);} function doubleClicked(event) { // get the x and y location // of the double click locationX = event.x; locationY = event.y; locString = "Mouse was double clicked at location: " + locationX + ", " + locationY; text(locString, 10, y); y = y + 20; console.log(event);} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/doubleClicked JavaScript-p5.js 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 calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 44937, "s": 44909, "text": "\n17 Jan, 2020" }, { "code": null, "e": 45217, "s": 44937, "text": "The doubleClicked() function is invoked whenever a mouse or pointing device causes a dblclick event. This happens when the pointing device is clicked twice in quick succession on a single element. The MouseEvent callback argument could be used to access the details of the click." }, { "code": null, "e": 45225, "s": 45217, "text": "Syntax:" }, { "code": null, "e": 45248, "s": 45225, "text": "doubleClicked([event])" }, { "code": null, "e": 45341, "s": 45248, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 45442, "s": 45341, "text": "event: This is an optional MouseEvent callback argument. It can be used to access the click details." }, { "code": null, "e": 45510, "s": 45442, "text": "The program below illustrate the doubleClicked() function in p5.js:" }, { "code": null, "e": 45566, "s": 45510, "text": "Example 1: Using double click to change the fill color." }, { "code": "let colorVal = 0; function setup() { createCanvas(500, 300); textSize(24);} function draw() { clear(); // apply fill based on the red component fill(colorVal, 128, 255 - colorVal) text(\"Double click to change the color\", 20, 20); circle(150, 150, 200);} function doubleClicked() { // change the value if // the event occurs if (colorVal < 255) colorVal += 50; else colorVal = 0;}", "e": 45970, "s": 45566, "text": null }, { "code": null, "e": 46036, "s": 45970, "text": "Output:Example 2: Accessing the details of the MouseEvent object." }, { "code": "let y = 60; function setup() { createCanvas(500, 200); textSize(16); text(\"Double click the mouse to see doubleClicked() function fire\", 10, 20);} function doubleClicked(event) { // get the x and y location // of the double click locationX = event.x; locationY = event.y; locString = \"Mouse was double clicked at location: \" + locationX + \", \" + locationY; text(locString, 10, y); y = y + 20; console.log(event);}", "e": 46470, "s": 46036, "text": null }, { "code": null, "e": 46478, "s": 46470, "text": "Output:" }, { "code": null, "e": 46615, "s": 46478, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 46672, "s": 46615, "text": "Reference: https://p5js.org/reference/#/p5/doubleClicked" }, { "code": null, "e": 46689, "s": 46672, "text": "JavaScript-p5.js" }, { "code": null, "e": 46700, "s": 46689, "text": "JavaScript" }, { "code": null, "e": 46717, "s": 46700, "text": "Web Technologies" }, { "code": null, "e": 46815, "s": 46717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46855, "s": 46815, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46900, "s": 46855, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46961, "s": 46900, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 47033, "s": 46961, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 47102, "s": 47033, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 47142, "s": 47102, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47175, "s": 47142, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47220, "s": 47175, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47263, "s": 47220, "text": "How to fetch data from an API in ReactJS ?" } ]
Golang program that uses func with variable argument list - GeeksforGeeks
10 May, 2020 In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis ..., then the function can accept any number of arguments for that parameter. Syntax of a variadic function: func f(elem ...Type) Here ... operator tells Golang program to store all arguments of Type in elem parameter. After that, Go create an elem variable of the type []Type. Therefore, all the values passed are stored in an elem parameter which is a slice. A slice can also be passed in the argument instead of the argument list, as finally function is converting them into a slice. For more information you can refer to Variadic Functions in Golang Advantages of using a Variadic Function: Passing a slice in a function is very easy. Useful when the number of parameters is unknown. Increases the readability of the program. Let’s see some of the examples to use functions with variable argument list: Example 1: // Go program that uses a function// with variable argument listpackage main // Importing required packagesimport ( "fmt") // Variadic function to return // the sum of the numbersfunc add(num ...int) int { sum := 0 for j := range num { sum += j } return sum} func main() { fmt.Println("Sum =", add(1, 2, 3, 4, 5, 7, 8, 6, 5, 4))} Output: Sum = 45 Example 2: A slice can also be used as an argument list. // Go program that uses a function// with variable argument list// Using a slice as the argument listpackage main // importing required modulesimport ( "fmt") // Function to check if an element// is present in the list or notfunc check(x int, v ...int) { flag := false index := 0 for i, j := range v { if j == x { flag = true index = i } } if flag { fmt.Println("Element ", x, " found at index:", index) } else { fmt.Println("Element not present in the list") }}func main() { el := []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9} check(1, el...) check(10, el...)} Output: Element 1 found at index: 1 Element not present in the list Go-Functions Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Time Durations in Golang Strings in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Defer Keyword in Golang Loops in Go Language Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n10 May, 2020" }, { "code": null, "e": 26018, "s": 25703, "text": "In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis ..., then the function can accept any number of arguments for that parameter." }, { "code": null, "e": 26049, "s": 26018, "text": "Syntax of a variadic function:" }, { "code": null, "e": 26070, "s": 26049, "text": "func f(elem ...Type)" }, { "code": null, "e": 26427, "s": 26070, "text": "Here ... operator tells Golang program to store all arguments of Type in elem parameter. After that, Go create an elem variable of the type []Type. Therefore, all the values passed are stored in an elem parameter which is a slice. A slice can also be passed in the argument instead of the argument list, as finally function is converting them into a slice." }, { "code": null, "e": 26494, "s": 26427, "text": "For more information you can refer to Variadic Functions in Golang" }, { "code": null, "e": 26535, "s": 26494, "text": "Advantages of using a Variadic Function:" }, { "code": null, "e": 26579, "s": 26535, "text": "Passing a slice in a function is very easy." }, { "code": null, "e": 26628, "s": 26579, "text": "Useful when the number of parameters is unknown." }, { "code": null, "e": 26670, "s": 26628, "text": "Increases the readability of the program." }, { "code": null, "e": 26747, "s": 26670, "text": "Let’s see some of the examples to use functions with variable argument list:" }, { "code": null, "e": 26758, "s": 26747, "text": "Example 1:" }, { "code": "// Go program that uses a function// with variable argument listpackage main // Importing required packagesimport ( \"fmt\") // Variadic function to return // the sum of the numbersfunc add(num ...int) int { sum := 0 for j := range num { sum += j } return sum} func main() { fmt.Println(\"Sum =\", add(1, 2, 3, 4, 5, 7, 8, 6, 5, 4))}", "e": 27116, "s": 26758, "text": null }, { "code": null, "e": 27124, "s": 27116, "text": "Output:" }, { "code": null, "e": 27133, "s": 27124, "text": "Sum = 45" }, { "code": null, "e": 27190, "s": 27133, "text": "Example 2: A slice can also be used as an argument list." }, { "code": "// Go program that uses a function// with variable argument list// Using a slice as the argument listpackage main // importing required modulesimport ( \"fmt\") // Function to check if an element// is present in the list or notfunc check(x int, v ...int) { flag := false index := 0 for i, j := range v { if j == x { flag = true index = i } } if flag { fmt.Println(\"Element \", x, \" found at index:\", index) } else { fmt.Println(\"Element not present in the list\") }}func main() { el := []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9} check(1, el...) check(10, el...)}", "e": 27831, "s": 27190, "text": null }, { "code": null, "e": 27839, "s": 27831, "text": "Output:" }, { "code": null, "e": 27902, "s": 27839, "text": "Element 1 found at index: 1\nElement not present in the list\n" }, { "code": null, "e": 27915, "s": 27902, "text": "Go-Functions" }, { "code": null, "e": 27930, "s": 27915, "text": "Golang-Program" }, { "code": null, "e": 27937, "s": 27930, "text": "Picked" }, { "code": null, "e": 27949, "s": 27937, "text": "Go Language" }, { "code": null, "e": 28047, "s": 27949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28093, "s": 28047, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28122, "s": 28093, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28147, "s": 28122, "text": "Time Durations in Golang" }, { "code": null, "e": 28165, "s": 28147, "text": "Strings in Golang" }, { "code": null, "e": 28186, "s": 28165, "text": "Structures in Golang" }, { "code": null, "e": 28241, "s": 28186, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28256, "s": 28241, "text": "Rune in Golang" }, { "code": null, "e": 28280, "s": 28256, "text": "Defer Keyword in Golang" }, { "code": null, "e": 28301, "s": 28280, "text": "Loops in Go Language" } ]
How to create multi-line strings in JavaScript? - GeeksforGeeks
22 Apr, 2019 The multi-line strings were not supported by JavaScript 2015 but when ES6 came out and introduced string literals. The ES6 supports multi-line strings. There are various ways to handle multi-line strings if older browser support is essential. Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter. Example: This example uses template literals to create multi-line strings. <!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class="multiline"></div> <p> Click on the button to insert multiline text </p> <button onclick="showMultiline()"> Click here </button> <script type="text/javascript"> function showMultiline() { multilineString = `<div> <h3>This is the heading</h3> <p> This is a paragraph. This uses template literals that were added in ES6 of JavaScript </p> </div>` document.querySelector('.multiline').innerHTML = multilineString; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using the backslash to escape the literal newlines: The other method that can be used to create multi-line strings is escaping every newline on each line. Example: This example uses the backslash to escape the literal newlines to create multi-line strings. <!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class="multiline"></div> <p> Click on the button to insert multiline text </p> <button onclick="showMultiline()"> Click here </button> <script type="text/javascript"> function showMultiline() { multilineString = "<div> \ <h3>This is the heading</h3> \ <p>This is a paragraph \ This uses backslashes in place\ of new lines</p> \ </div>" document.querySelector('.multiline').innerHTML = multilineString; } </script></body></html> Output: Before Clicking the button: After Clicking the button: Method 3: Concatenating the individual strings together: The simplest, but the cumbersome way is separating each line as a string and concatenating into one final string. Example: This example concatenate the string to create multi-line strings. <!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class="multiline"></div> <p> Click on the button to insert multiline text </p> <button onclick="showMultiline()"> Click here </button> <script type="text/javascript"> function showMultiline() { multilineString = "<div>" + "<h3>This is the heading</h3>" + "<p>This is a paragraph" + "This uses simple concatenation " + "of strings for every line</p> " + "</div>" document.querySelector('.multiline').innerHTML = multilineString; } </script></body> </html> Output: Before Clicking the button: After Clicking the button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in 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": 31305, "s": 31277, "text": "\n22 Apr, 2019" }, { "code": null, "e": 31548, "s": 31305, "text": "The multi-line strings were not supported by JavaScript 2015 but when ES6 came out and introduced string literals. The ES6 supports multi-line strings. There are various ways to handle multi-line strings if older browser support is essential." }, { "code": null, "e": 31705, "s": 31548, "text": "Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter." }, { "code": null, "e": 31780, "s": 31705, "text": "Example: This example uses template literals to create multi-line strings." }, { "code": "<!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class=\"multiline\"></div> <p> Click on the button to insert multiline text </p> <button onclick=\"showMultiline()\"> Click here </button> <script type=\"text/javascript\"> function showMultiline() { multilineString = `<div> <h3>This is the heading</h3> <p> This is a paragraph. This uses template literals that were added in ES6 of JavaScript </p> </div>` document.querySelector('.multiline').innerHTML = multilineString; } </script></body> </html>", "e": 32769, "s": 31780, "text": null }, { "code": null, "e": 32777, "s": 32769, "text": "Output:" }, { "code": null, "e": 32805, "s": 32777, "text": "Before clicking the button:" }, { "code": null, "e": 32832, "s": 32805, "text": "After clicking the button:" }, { "code": null, "e": 32997, "s": 32832, "text": "Method 2: Using the backslash to escape the literal newlines: The other method that can be used to create multi-line strings is escaping every newline on each line." }, { "code": null, "e": 33099, "s": 32997, "text": "Example: This example uses the backslash to escape the literal newlines to create multi-line strings." }, { "code": "<!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class=\"multiline\"></div> <p> Click on the button to insert multiline text </p> <button onclick=\"showMultiline()\"> Click here </button> <script type=\"text/javascript\"> function showMultiline() { multilineString = \"<div> \\ <h3>This is the heading</h3> \\ <p>This is a paragraph \\ This uses backslashes in place\\ of new lines</p> \\ </div>\" document.querySelector('.multiline').innerHTML = multilineString; } </script></body></html>", "e": 34015, "s": 33099, "text": null }, { "code": null, "e": 34023, "s": 34015, "text": "Output:" }, { "code": null, "e": 34051, "s": 34023, "text": "Before Clicking the button:" }, { "code": null, "e": 34078, "s": 34051, "text": "After Clicking the button:" }, { "code": null, "e": 34249, "s": 34078, "text": "Method 3: Concatenating the individual strings together: The simplest, but the cumbersome way is separating each line as a string and concatenating into one final string." }, { "code": null, "e": 34324, "s": 34249, "text": "Example: This example concatenate the string to create multi-line strings." }, { "code": "<!DOCTYPE html><html> <head> <title> Create multi-line strings </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to create multi-line strings in JavaScript? </b> <div class=\"multiline\"></div> <p> Click on the button to insert multiline text </p> <button onclick=\"showMultiline()\"> Click here </button> <script type=\"text/javascript\"> function showMultiline() { multilineString = \"<div>\" + \"<h3>This is the heading</h3>\" + \"<p>This is a paragraph\" + \"This uses simple concatenation \" + \"of strings for every line</p> \" + \"</div>\" document.querySelector('.multiline').innerHTML = multilineString; } </script></body> </html>", "e": 35269, "s": 34324, "text": null }, { "code": null, "e": 35277, "s": 35269, "text": "Output:" }, { "code": null, "e": 35305, "s": 35277, "text": "Before Clicking the button:" }, { "code": null, "e": 35332, "s": 35305, "text": "After Clicking the button:" }, { "code": null, "e": 35348, "s": 35332, "text": "JavaScript-Misc" }, { "code": null, "e": 35355, "s": 35348, "text": "Picked" }, { "code": null, "e": 35366, "s": 35355, "text": "JavaScript" }, { "code": null, "e": 35383, "s": 35366, "text": "Web Technologies" }, { "code": null, "e": 35410, "s": 35383, "text": "Web technologies Questions" }, { "code": null, "e": 35508, "s": 35410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35548, "s": 35508, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35593, "s": 35548, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35654, "s": 35593, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35726, "s": 35654, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 35795, "s": 35726, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35835, "s": 35795, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35868, "s": 35835, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35913, "s": 35868, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35956, "s": 35913, "text": "How to fetch data from an API in ReactJS ?" } ]
Web API WebRTC.getUserMedia() Method - GeeksforGeeks
02 Mar, 2021 The MediaDevices.getUserMedia() is a part of the webRTC media capture API and is used to get access to the camera and the microphone connected to the user device (user computer, smartphone, etc.) from the browser. When getUserMedia() is invoked, the browser asks for permission from the user to use the media inputs (camera or microphone or both) connected to the user device. Syntax : navigator.mediaDevices.getUserMedia( MediaStreamConstraints ) .then( MediaStream => { // Code that uses the MediaStream }).catch( error => { // Code to handle the error }); Using the getUserMedia() API: getUserMedia() can be accessed by accessing the navigator.mediaDevices singleton object that offers various methods for accessing the camera, microphone as well as screen sharing. When getUserMedia() is invoked, the browser prompts the User for permission to access the available device camera or microphone (based on the given MediaStreamConstraints parameter). If the User gives the permission, then it returns a Promise that resolves to a MediaStream. Note: getUserMedia() can be accessed through navigator.getUserMedia() also, but it is deprecated and hence not recommended. What is a MediaStream? MediaStream is simply a stream of audio or video content data that is not saved in the device memory, rather it is just “passed” to a specific video or audio element as the source data. Note that the media content data is not saved in the running memory, which means if you don’t have a “pre-downloaded” video or audio data, still you can use the media stream to play the video or audio content as it does not need to be downloaded. What is MediaStreamConstraints? MediaStreamConstraints is an object containing all the constraints like what type of data is/are to be streamed (video or audio or both ), what should be the resolution of the camera etc. const mediaStreamConstraints = { audio: true, video: true }; // It basically tells the getUserMedia() to // open both the camera and the microphone const stream = await navigator.mediaDevices .getUserMedia(mediaStreamConstraints); Using the MediaStream received from the getUserMedia(): If the user gives permission to access the camera and the microphone, then this method returns a promise whose fulfillment handler receives a MediaStream that we can use in the handler function. Usually, we pass the received MediaStream to a video or audio element as the source (using the srcObject attribute of video or audio element). Javascript navigator.mediaDevices.getUserMedia( MediaStreamConstraints ) .then( MediaStream => { /*assuming that there is a video tag having an id 'video' in the index.html*/ const videoElem = document.getElementById( 'video'); /*it is important to use the srcObject attribute and not the src attribute because, the src attribute does not support the mediaStream as a value*/ videoElem.srcObject = mediaStream; //Don't forget to set the autoplay attribute to true video.autoplay = true; }).catch( error => { //code to handle the error }); //Or using async/await — async function accessCamera() { const videoElem = document.getElementById( 'video'); let stream = null; try{ stream = await navigator.mediaDevices.getUserMedia( MediaStreamConstraints ); //adding the received stream to the source of the video element videoElem.srcObject = stream; videoElem.autoplay = true; }catch(err) { //code to handle the error }} What if the user does not give permission to access the camera and microphone ? If the User denies giving permission then getUserMedia() throws a NotAllowedError that we can catch using the catch block. If the user simply ignores the prompt, then nothing happens( the promise is never resolved nor rejected). Now, let’s discuss the MediaStreamConstraints with more details: MediaStreamConstraints: This is basically an object containing all the information regarding what type of media to use, what should be the resolution of the camera, which device to use as the media input etc. The simplest MediaStreamConstraints object looks like this — const constraints = { audio: false, // or true if you want to enable audio video: true // or false if you want to disable video }; // Includes only the video media if available MediaStreamConstraints object has only two properties(members): audio and video, both of them accepts a boolean value that tells the browser whether to include that specific media content in the resulting media stream. “true” makes the media “required” in the resulting media stream, if that “required” media is not available then getUserMedia() throws “NotFoundError”. For example, getUserMedia() will throw “NotFoundError” for the above constraints if the user device doesn’t have a camera. Additionally, you can add more constraints to use media content with some preferred capabilities : You can specify the resolution of the camera the browser should prefer: Javascript /* This constraints object tells the browser to use the camera having 1200 X 800 resolution if available*/const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { width: 1200, height: 800 }// Inherently sets video content to true or "required"}; “prefer” because the above constraints object does not ensure that the browser will use a camera with that resolution. The browser first checks if there is any type of media input that matches the given constraints, and if there is any then only the browser uses that matching media input. But if there are none that match the given constraints, then the browser uses the device with the closest match. But if you want to make some capabilities “required” or mandatory or apply some limit on the capabilities, then you can use various key-words: The “min” and “max” keywords : As the names of the key-words suggest, the “min” key-word tells the browser that the corresponding media is required to have at least the given capabilities, similarly, the “max” key-word tells the browser that it is mandatory for the corresponding media to have at-most the specified constraint. If no such media input device meets the given constraints, then the returned promise is rejected with “NotFoundError”. Javascript /* This constraints object tells the browser to use the camera having resolution between 1200 X 720 and 1600 X 1080 resolutionif available otherwise the returned promise is rejected with "NotFoundError" */const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { width: { min: 1200, max: 1600 }, height: { min: 720, max: 1080 } }}; // Inherently sets video content to true or "required" The “deviceId” keyword : The “deviceId” property asks the browser to use the media input device having the given deviceId if available otherwise use other available input devices. The deviceId can be obtained from the navigator.mediaDevices.enumerateDevices() method that returns a promise that resolves to a list of connected cameras, microphones, headsets, etc. Each connected device has a unique and unguessable id called “deviceId”. Javascript //initializing the deviceId with nulllet deviceId = null; //returns a promise that resolves to a list of//connected devicesnavigator.mediaDevices.enumerateDevices().then( devices => { devices.forEach(device => { //if the device is a video input //then get its deviceId if(device.kind === 'videoinput'){ deviceId = device.deviceId; } });}).catch(err => { //handle the error}); /* This constraints object tells the browser touse the camera having the given deviceId if available otherwise use other available devices*/const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { deviceId: deviceId }}; // Inherently sets video content to true or "required" 3. The “exact” keyword : The “exact” property tells the browser that it is mandatory to use a media having exactly the corresponding constraint Javascript // This constraints object tells the browser to use the camera having exactly the given deviceId if available otherwise the returned promise is rejected with "NotFoundError" */const constraints = { audio: {/* browser prefers the device having the given deviceId if available otherwise use other devices*/ deviceId: audioDeviceId }, video: { deviceId: { exact: someId } }}; // Inherently sets video and audio content to true or "required" 4. The “ideal” property: The “ideal” property tells the browser that the given constraint value is the ideal value and the device having the “ideal” constraint should be used. Any normal property values are inherently ideal Javascript /* This constraints object tells the browserto use the camera having 1200 X 800resolution if available */const constraints = { audio: true //enable the audio media track video: { width: 1200, // same as width: {ideal: 1200} height: 800 // same as height: {ideal: 800} }}; // Inherently sets video content to true or "required" 5. The “facingMode” property: Specifies whether to use the front camera or the rear camera if available. It is mainly used for mobile devices. Javascript const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { facingMode: "user" //prefers front camera if available// or facingMode: "environment" --> perfers rear camera if available }}; // Inherently sets video content to true or "required" Example of using getUserMedia() : HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; } video { background-color: black; margin-bottom: 1rem; } #error { color: red; padding: 0.6rem; background-color: rgb(236 157 157); margin-bottom: 0.6rem; display: none; } </style> <title>GetUserMedia demo</title></head> <body> <h1> WebRTC getUserMedia() demo</h1> <!-- If you use the playsinline attribute then the video is played "inline". If you omit this attribute then it works normal in the desktop browsers, but for the mobile browsers, the video takes the fullscreen by default. And don't forget to use the autoplay attribute--> <video id='video' width="600" height="300" autoplay playsinline> Sorry, video element not supported in your browser </video> <div id="error"></div> <button onclick="openCamera()"> Open Camera</button> <script> const videoElem = document.getElementById('video'); const errorElem = document.getElementById('error'); //Declare the MediaStreamConstraints object const constraints = { audio: true, video: true } function openCamera() {//Ask the User for the access of the device camera and microphone navigator.mediaDevices.getUserMedia(constraints) .then(mediaStream => { /* The received mediaStream contains both the video and audio media data*/ /*Add the mediaStream directly to the source of the video element using the srcObject attribute*/ videoElem.srcObject = mediaStream; }).catch(err => { // handling the error if any errorElem.innerHTML = err; errorElem.style.display = "block"; }); } </script></body> </html> Output: Now if you click the “Open Camera” button, the browser will ask for your permission, if you allow, then you will see yourself on the screen. But if you deny, then you can see the error right below the video element in a red box: How to close the camera and the microphone: Till now, we have discussed how to open the camera from the browser, we have done nothing to stop using the camera and the microphone. Though, if you close the tab or window, the browser automatically stops using the camera and the microphone. But if you want to close the camera and the microphone yourself, then you can follow the below code Example 2: First, add a “Close Camera” button and “closeCamera() method. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; } video { background-color: black; margin-bottom: 1rem; } #error { color: red; padding: 0.6rem; background-color: rgb(236 157 157); margin-bottom: 0.6rem; display: none; } </style> <title>GetUserMedia demo</title></head> <body> <h1> WebRTC getUserMedia() demo</h1> <!-- If you use the playsinline attribute then the video is played "inline". If you omit this attribute then it works normal in the desktop browsers, but for the mobile browsers, the video takes the fullscreen by default. And don't forget to use the autoplay attribute--> <video id='video' width="600" height="300" autoplay playsinline> Sorry, video element not supported in your browsers </video> <div id="error"></div> <div id="button-container"> <button onclick="openCamera()"> Open Camera</button> <!-- Close Camera button --> <button onclick='closeCamera()'>Close Camera</button> </div> <script> const videoElem = document.getElementById('video'); const errorElem = document.getElementById('error'); let receivedMediaStream = null; //Declare the MediaStreamConstraints object const constraints = { audio: true, video: true } function openCamera() {//Ask the User for the access of the device camera and microphone navigator.mediaDevices.getUserMedia(constraints) .then(mediaStream => { // The received mediaStream contains both the // video and audio media data //Add the mediaStream directly to the source of the video element // using the srcObject attribute videoElem.srcObject = mediaStream; // make the received mediaStream available globally receivedMediaStream = mediaStream; }).catch(err => { // handling the error if any errorElem.innerHTML = err; errorElem.style.display = "block"; }); } const closeCamera = () => { if (!receivedMediaStream) { errorElem.innerHTML = "Camera is already closed!"; errorElem.style.display = "block"; } else {/* MediaStream.getTracks() returns an array of all the MediaStreamTracks being used in the received mediaStreamwe can iterate through all the mediaTracks and stop all the mediaTracks by calling its stop() method*/ receivedMediaStream.getTracks().forEach(mediaTrack => { mediaTrack.stop(); }); errorElem.innerHTML = "Camera closed successfully!" errorElem.style.display = "block"; } } </script></body> </html> Output: Before: After click “Close Camera” button: The closeCamera() method checks if the camera and the microphone both are closed or not by checking the receivedMediaStream variable. If it is null, it means the camera and the microphone both are closed, else it calls the getTracks() method of the received MediaStream which returns an array of MediaStreamTracks. You can stop those media tracks by calling its stop() method. Web-API 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 Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n02 Mar, 2021" }, { "code": null, "e": 26922, "s": 26545, "text": "The MediaDevices.getUserMedia() is a part of the webRTC media capture API and is used to get access to the camera and the microphone connected to the user device (user computer, smartphone, etc.) from the browser. When getUserMedia() is invoked, the browser asks for permission from the user to use the media inputs (camera or microphone or both) connected to the user device." }, { "code": null, "e": 26931, "s": 26922, "text": "Syntax :" }, { "code": null, "e": 27135, "s": 26931, "text": "navigator.mediaDevices.getUserMedia( MediaStreamConstraints )\n .then( MediaStream => {\n // Code that uses the MediaStream\n }).catch( error => {\n // Code to handle the error\n });" }, { "code": null, "e": 27621, "s": 27135, "text": "Using the getUserMedia() API: getUserMedia() can be accessed by accessing the navigator.mediaDevices singleton object that offers various methods for accessing the camera, microphone as well as screen sharing. When getUserMedia() is invoked, the browser prompts the User for permission to access the available device camera or microphone (based on the given MediaStreamConstraints parameter). If the User gives the permission, then it returns a Promise that resolves to a MediaStream. " }, { "code": null, "e": 27745, "s": 27621, "text": "Note: getUserMedia() can be accessed through navigator.getUserMedia() also, but it is deprecated and hence not recommended." }, { "code": null, "e": 27768, "s": 27745, "text": "What is a MediaStream?" }, { "code": null, "e": 28201, "s": 27768, "text": "MediaStream is simply a stream of audio or video content data that is not saved in the device memory, rather it is just “passed” to a specific video or audio element as the source data. Note that the media content data is not saved in the running memory, which means if you don’t have a “pre-downloaded” video or audio data, still you can use the media stream to play the video or audio content as it does not need to be downloaded." }, { "code": null, "e": 28233, "s": 28201, "text": "What is MediaStreamConstraints?" }, { "code": null, "e": 28422, "s": 28233, "text": "MediaStreamConstraints is an object containing all the constraints like what type of data is/are to be streamed (video or audio or both ), what should be the resolution of the camera etc. " }, { "code": null, "e": 28666, "s": 28422, "text": "const mediaStreamConstraints = {\n audio: true,\n video: true\n}; \n\n// It basically tells the getUserMedia() to \n// open both the camera and the microphone\nconst stream = await navigator.mediaDevices\n .getUserMedia(mediaStreamConstraints);" }, { "code": null, "e": 29063, "s": 28666, "text": "Using the MediaStream received from the getUserMedia(): If the user gives permission to access the camera and the microphone, then this method returns a promise whose fulfillment handler receives a MediaStream that we can use in the handler function. Usually, we pass the received MediaStream to a video or audio element as the source (using the srcObject attribute of video or audio element). " }, { "code": null, "e": 29074, "s": 29063, "text": "Javascript" }, { "code": "navigator.mediaDevices.getUserMedia( MediaStreamConstraints ) .then( MediaStream => { /*assuming that there is a video tag having an id 'video' in the index.html*/ const videoElem = document.getElementById( 'video'); /*it is important to use the srcObject attribute and not the src attribute because, the src attribute does not support the mediaStream as a value*/ videoElem.srcObject = mediaStream; //Don't forget to set the autoplay attribute to true video.autoplay = true; }).catch( error => { //code to handle the error }); //Or using async/await — async function accessCamera() { const videoElem = document.getElementById( 'video'); let stream = null; try{ stream = await navigator.mediaDevices.getUserMedia( MediaStreamConstraints ); //adding the received stream to the source of the video element videoElem.srcObject = stream; videoElem.autoplay = true; }catch(err) { //code to handle the error }}", "e": 30190, "s": 29074, "text": null }, { "code": null, "e": 30270, "s": 30190, "text": "What if the user does not give permission to access the camera and microphone ?" }, { "code": null, "e": 30500, "s": 30270, "text": "If the User denies giving permission then getUserMedia() throws a NotAllowedError that we can catch using the catch block. If the user simply ignores the prompt, then nothing happens( the promise is never resolved nor rejected). " }, { "code": null, "e": 30566, "s": 30500, "text": "Now, let’s discuss the MediaStreamConstraints with more details: " }, { "code": null, "e": 30590, "s": 30566, "text": "MediaStreamConstraints:" }, { "code": null, "e": 30836, "s": 30590, "text": "This is basically an object containing all the information regarding what type of media to use, what should be the resolution of the camera, which device to use as the media input etc. The simplest MediaStreamConstraints object looks like this —" }, { "code": null, "e": 31026, "s": 30836, "text": "const constraints = {\n audio: false, // or true if you want to enable audio\n video: true // or false if you want to disable video\n}; // Includes only the video media if available" }, { "code": null, "e": 31520, "s": 31026, "text": "MediaStreamConstraints object has only two properties(members): audio and video, both of them accepts a boolean value that tells the browser whether to include that specific media content in the resulting media stream. “true” makes the media “required” in the resulting media stream, if that “required” media is not available then getUserMedia() throws “NotFoundError”. For example, getUserMedia() will throw “NotFoundError” for the above constraints if the user device doesn’t have a camera." }, { "code": null, "e": 31620, "s": 31520, "text": "Additionally, you can add more constraints to use media content with some preferred capabilities : " }, { "code": null, "e": 31692, "s": 31620, "text": "You can specify the resolution of the camera the browser should prefer:" }, { "code": null, "e": 31703, "s": 31692, "text": "Javascript" }, { "code": "/* This constraints object tells the browser to use the camera having 1200 X 800 resolution if available*/const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { width: 1200, height: 800 }// Inherently sets video content to true or \"required\"};", "e": 32037, "s": 31703, "text": null }, { "code": null, "e": 32441, "s": 32037, "text": "“prefer” because the above constraints object does not ensure that the browser will use a camera with that resolution. The browser first checks if there is any type of media input that matches the given constraints, and if there is any then only the browser uses that matching media input. But if there are none that match the given constraints, then the browser uses the device with the closest match. " }, { "code": null, "e": 32584, "s": 32441, "text": "But if you want to make some capabilities “required” or mandatory or apply some limit on the capabilities, then you can use various key-words:" }, { "code": null, "e": 32616, "s": 32584, "text": "The “min” and “max” keywords : " }, { "code": null, "e": 33033, "s": 32616, "text": "As the names of the key-words suggest, the “min” key-word tells the browser that the corresponding media is required to have at least the given capabilities, similarly, the “max” key-word tells the browser that it is mandatory for the corresponding media to have at-most the specified constraint. If no such media input device meets the given constraints, then the returned promise is rejected with “NotFoundError”." }, { "code": null, "e": 33044, "s": 33033, "text": "Javascript" }, { "code": "/* This constraints object tells the browser to use the camera having resolution between 1200 X 720 and 1600 X 1080 resolutionif available otherwise the returned promise is rejected with \"NotFoundError\" */const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { width: { min: 1200, max: 1600 }, height: { min: 720, max: 1080 } }}; // Inherently sets video content to true or \"required\"", "e": 33594, "s": 33044, "text": null }, { "code": null, "e": 33619, "s": 33594, "text": "The “deviceId” keyword :" }, { "code": null, "e": 34032, "s": 33619, "text": "The “deviceId” property asks the browser to use the media input device having the given deviceId if available otherwise use other available input devices. The deviceId can be obtained from the navigator.mediaDevices.enumerateDevices() method that returns a promise that resolves to a list of connected cameras, microphones, headsets, etc. Each connected device has a unique and unguessable id called “deviceId”." }, { "code": null, "e": 34043, "s": 34032, "text": "Javascript" }, { "code": "//initializing the deviceId with nulllet deviceId = null; //returns a promise that resolves to a list of//connected devicesnavigator.mediaDevices.enumerateDevices().then( devices => { devices.forEach(device => { //if the device is a video input //then get its deviceId if(device.kind === 'videoinput'){ deviceId = device.deviceId; } });}).catch(err => { //handle the error}); /* This constraints object tells the browser touse the camera having the given deviceId if available otherwise use other available devices*/const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { deviceId: deviceId }}; // Inherently sets video content to true or \"required\"", "e": 34821, "s": 34043, "text": null }, { "code": null, "e": 34846, "s": 34821, "text": "3. The “exact” keyword :" }, { "code": null, "e": 34966, "s": 34846, "text": "The “exact” property tells the browser that it is mandatory to use a media having exactly the corresponding constraint " }, { "code": null, "e": 34977, "s": 34966, "text": "Javascript" }, { "code": "// This constraints object tells the browser to use the camera having exactly the given deviceId if available otherwise the returned promise is rejected with \"NotFoundError\" */const constraints = { audio: {/* browser prefers the device having the given deviceId if available otherwise use other devices*/ deviceId: audioDeviceId }, video: { deviceId: { exact: someId } }}; // Inherently sets video and audio content to true or \"required\"", "e": 35477, "s": 34977, "text": null }, { "code": null, "e": 35502, "s": 35477, "text": "4. The “ideal” property:" }, { "code": null, "e": 35702, "s": 35502, "text": "The “ideal” property tells the browser that the given constraint value is the ideal value and the device having the “ideal” constraint should be used. Any normal property values are inherently ideal " }, { "code": null, "e": 35713, "s": 35702, "text": "Javascript" }, { "code": "/* This constraints object tells the browserto use the camera having 1200 X 800resolution if available */const constraints = { audio: true //enable the audio media track video: { width: 1200, // same as width: {ideal: 1200} height: 800 // same as height: {ideal: 800} }}; // Inherently sets video content to true or \"required\"", "e": 36075, "s": 35713, "text": null }, { "code": null, "e": 36106, "s": 36075, "text": "5. The “facingMode” property: " }, { "code": null, "e": 36219, "s": 36106, "text": "Specifies whether to use the front camera or the rear camera if available. It is mainly used for mobile devices." }, { "code": null, "e": 36230, "s": 36219, "text": "Javascript" }, { "code": "const constraints = {//disables the audio media content in the resulting media stream audio: false, video: { facingMode: \"user\" //prefers front camera if available// or facingMode: \"environment\" --> perfers rear camera if available }}; // Inherently sets video content to true or \"required\"", "e": 36548, "s": 36230, "text": null }, { "code": null, "e": 36582, "s": 36548, "text": "Example of using getUserMedia() :" }, { "code": null, "e": 36587, "s": 36582, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> body { text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; } video { background-color: black; margin-bottom: 1rem; } #error { color: red; padding: 0.6rem; background-color: rgb(236 157 157); margin-bottom: 0.6rem; display: none; } </style> <title>GetUserMedia demo</title></head> <body> <h1> WebRTC getUserMedia() demo</h1> <!-- If you use the playsinline attribute then the video is played \"inline\". If you omit this attribute then it works normal in the desktop browsers, but for the mobile browsers, the video takes the fullscreen by default. And don't forget to use the autoplay attribute--> <video id='video' width=\"600\" height=\"300\" autoplay playsinline> Sorry, video element not supported in your browser </video> <div id=\"error\"></div> <button onclick=\"openCamera()\"> Open Camera</button> <script> const videoElem = document.getElementById('video'); const errorElem = document.getElementById('error'); //Declare the MediaStreamConstraints object const constraints = { audio: true, video: true } function openCamera() {//Ask the User for the access of the device camera and microphone navigator.mediaDevices.getUserMedia(constraints) .then(mediaStream => { /* The received mediaStream contains both the video and audio media data*/ /*Add the mediaStream directly to the source of the video element using the srcObject attribute*/ videoElem.srcObject = mediaStream; }).catch(err => { // handling the error if any errorElem.innerHTML = err; errorElem.style.display = \"block\"; }); } </script></body> </html>", "e": 38865, "s": 36587, "text": null }, { "code": null, "e": 38874, "s": 38865, "text": "Output: " }, { "code": null, "e": 39103, "s": 38874, "text": "Now if you click the “Open Camera” button, the browser will ask for your permission, if you allow, then you will see yourself on the screen. But if you deny, then you can see the error right below the video element in a red box:" }, { "code": null, "e": 39147, "s": 39103, "text": "How to close the camera and the microphone:" }, { "code": null, "e": 39491, "s": 39147, "text": "Till now, we have discussed how to open the camera from the browser, we have done nothing to stop using the camera and the microphone. Though, if you close the tab or window, the browser automatically stops using the camera and the microphone. But if you want to close the camera and the microphone yourself, then you can follow the below code" }, { "code": null, "e": 39564, "s": 39491, "text": "Example 2: First, add a “Close Camera” button and “closeCamera() method." }, { "code": null, "e": 39569, "s": 39564, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> body { text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; } video { background-color: black; margin-bottom: 1rem; } #error { color: red; padding: 0.6rem; background-color: rgb(236 157 157); margin-bottom: 0.6rem; display: none; } </style> <title>GetUserMedia demo</title></head> <body> <h1> WebRTC getUserMedia() demo</h1> <!-- If you use the playsinline attribute then the video is played \"inline\". If you omit this attribute then it works normal in the desktop browsers, but for the mobile browsers, the video takes the fullscreen by default. And don't forget to use the autoplay attribute--> <video id='video' width=\"600\" height=\"300\" autoplay playsinline> Sorry, video element not supported in your browsers </video> <div id=\"error\"></div> <div id=\"button-container\"> <button onclick=\"openCamera()\"> Open Camera</button> <!-- Close Camera button --> <button onclick='closeCamera()'>Close Camera</button> </div> <script> const videoElem = document.getElementById('video'); const errorElem = document.getElementById('error'); let receivedMediaStream = null; //Declare the MediaStreamConstraints object const constraints = { audio: true, video: true } function openCamera() {//Ask the User for the access of the device camera and microphone navigator.mediaDevices.getUserMedia(constraints) .then(mediaStream => { // The received mediaStream contains both the // video and audio media data //Add the mediaStream directly to the source of the video element // using the srcObject attribute videoElem.srcObject = mediaStream; // make the received mediaStream available globally receivedMediaStream = mediaStream; }).catch(err => { // handling the error if any errorElem.innerHTML = err; errorElem.style.display = \"block\"; }); } const closeCamera = () => { if (!receivedMediaStream) { errorElem.innerHTML = \"Camera is already closed!\"; errorElem.style.display = \"block\"; } else {/* MediaStream.getTracks() returns an array of all the MediaStreamTracks being used in the received mediaStreamwe can iterate through all the mediaTracks and stop all the mediaTracks by calling its stop() method*/ receivedMediaStream.getTracks().forEach(mediaTrack => { mediaTrack.stop(); }); errorElem.innerHTML = \"Camera closed successfully!\" errorElem.style.display = \"block\"; } } </script></body> </html>", "e": 42873, "s": 39569, "text": null }, { "code": null, "e": 42881, "s": 42873, "text": "Output:" }, { "code": null, "e": 42889, "s": 42881, "text": "Before:" }, { "code": null, "e": 42924, "s": 42889, "text": "After click “Close Camera” button:" }, { "code": null, "e": 43301, "s": 42924, "text": "The closeCamera() method checks if the camera and the microphone both are closed or not by checking the receivedMediaStream variable. If it is null, it means the camera and the microphone both are closed, else it calls the getTracks() method of the received MediaStream which returns an array of MediaStreamTracks. You can stop those media tracks by calling its stop() method." }, { "code": null, "e": 43309, "s": 43301, "text": "Web-API" }, { "code": null, "e": 43320, "s": 43309, "text": "JavaScript" }, { "code": null, "e": 43337, "s": 43320, "text": "Web Technologies" }, { "code": null, "e": 43435, "s": 43337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43475, "s": 43435, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43536, "s": 43475, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 43577, "s": 43536, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 43599, "s": 43577, "text": "JavaScript | Promises" }, { "code": null, "e": 43653, "s": 43599, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 43693, "s": 43653, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43726, "s": 43693, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 43769, "s": 43726, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 43819, "s": 43769, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Inter-Switch Link (ISL) and IEEE 802.1Q - GeeksforGeeks
19 Oct, 2021 VLANs are used to divide broadcast domain at layer 2. By default, all the switch ports are in VLAN 1. Configuration of VLANs other than VLAN 1 then to carry traffic of these VLANs, user has to make a switch port trunk which is connected to another switch. If the frame is forwarded out to an access link then it is considered that the frame belongs to the VLAN which is configured on that switch port. But if the frame is forwarded out to a trunk link then how did the other device know that the traffic belongs to which VLAN? There comes the concept of VLAN identification methods. VLAN Identification methods –If the frame is forwarded out to a trunk link then a header or tag is added to the frame header which specifies the VLAN to which the frame belongs. The frame is encapsulated at the sender’s switch and removed at the receiver’s switch and then forwarded out to the ports which belongs to that VLAN (according to the processing of switch). There are 2 VLAN identification methods: Inter-Switch Link (ISL) –This is a VLAN identification method in which VLAN information is explicitly tagged onto Ethernet frame. ISL is proprietary to CISCO switches. ISL functions at layer 2 by encapsulating a data frame with a new header and by performing a new cyclic redundancy check (CRC).In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN.ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged.The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q.Configuration (ISL):Switch(config)#interface Fa0/1 Switch(config-if)#switchport trunk encapsulation isl Switch(config-if)#switchport mode trunk802.1Q –It is IEEE standard method of frame tagging. If user wants to trunk between a Cisco switch link and a different brand switch link, then have to use 802.1Q encapsulation for the trunk to work.In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN.Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan.Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link.Configuration (802.1Q) :Switch(config)#interface Fa 0/1 Switch(config-if)#switchport trunk encapsulation 802.1q Switch(config-if)#switchport mode trunk Inter-Switch Link (ISL) –This is a VLAN identification method in which VLAN information is explicitly tagged onto Ethernet frame. ISL is proprietary to CISCO switches. ISL functions at layer 2 by encapsulating a data frame with a new header and by performing a new cyclic redundancy check (CRC).In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN.ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged.The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q.Configuration (ISL):Switch(config)#interface Fa0/1 Switch(config-if)#switchport trunk encapsulation isl Switch(config-if)#switchport mode trunk In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN. ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged. The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q. Configuration (ISL): Switch(config)#interface Fa0/1 Switch(config-if)#switchport trunk encapsulation isl Switch(config-if)#switchport mode trunk 802.1Q –It is IEEE standard method of frame tagging. If user wants to trunk between a Cisco switch link and a different brand switch link, then have to use 802.1Q encapsulation for the trunk to work.In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN.Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan.Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link.Configuration (802.1Q) :Switch(config)#interface Fa 0/1 Switch(config-if)#switchport trunk encapsulation 802.1q Switch(config-if)#switchport mode trunk In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN. Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan. Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link. Configuration (802.1Q) : Switch(config)#interface Fa 0/1 Switch(config-if)#switchport trunk encapsulation 802.1q Switch(config-if)#switchport mode trunk niharikatanwar61 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Implementation of Diffie-Hellman Algorithm User Datagram Protocol (UDP) Socket Programming in Java Hamming Code in Computer Network Advanced Encryption Standard (AES) Distance Vector Routing (DVR) Protocol Types of area networks - LAN, MAN and WAN Error Detection in Computer Networks Network Address Translation (NAT)
[ { "code": null, "e": 25461, "s": 25433, "text": "\n19 Oct, 2021" }, { "code": null, "e": 26044, "s": 25461, "text": "VLANs are used to divide broadcast domain at layer 2. By default, all the switch ports are in VLAN 1. Configuration of VLANs other than VLAN 1 then to carry traffic of these VLANs, user has to make a switch port trunk which is connected to another switch. If the frame is forwarded out to an access link then it is considered that the frame belongs to the VLAN which is configured on that switch port. But if the frame is forwarded out to a trunk link then how did the other device know that the traffic belongs to which VLAN? There comes the concept of VLAN identification methods." }, { "code": null, "e": 26412, "s": 26044, "text": "VLAN Identification methods –If the frame is forwarded out to a trunk link then a header or tag is added to the frame header which specifies the VLAN to which the frame belongs. The frame is encapsulated at the sender’s switch and removed at the receiver’s switch and then forwarded out to the ports which belongs to that VLAN (according to the processing of switch)." }, { "code": null, "e": 26453, "s": 26412, "text": "There are 2 VLAN identification methods:" }, { "code": null, "e": 28587, "s": 26453, "text": "Inter-Switch Link (ISL) –This is a VLAN identification method in which VLAN information is explicitly tagged onto Ethernet frame. ISL is proprietary to CISCO switches. ISL functions at layer 2 by encapsulating a data frame with a new header and by performing a new cyclic redundancy check (CRC).In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN.ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged.The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q.Configuration (ISL):Switch(config)#interface Fa0/1\nSwitch(config-if)#switchport trunk encapsulation isl\nSwitch(config-if)#switchport mode trunk802.1Q –It is IEEE standard method of frame tagging. If user wants to trunk between a Cisco switch link and a different brand switch link, then have to use 802.1Q encapsulation for the trunk to work.In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN.Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan.Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link.Configuration (802.1Q) :Switch(config)#interface Fa 0/1\nSwitch(config-if)#switchport trunk encapsulation 802.1q\nSwitch(config-if)#switchport mode trunk" }, { "code": null, "e": 29603, "s": 28587, "text": "Inter-Switch Link (ISL) –This is a VLAN identification method in which VLAN information is explicitly tagged onto Ethernet frame. ISL is proprietary to CISCO switches. ISL functions at layer 2 by encapsulating a data frame with a new header and by performing a new cyclic redundancy check (CRC).In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN.ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged.The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q.Configuration (ISL):Switch(config)#interface Fa0/1\nSwitch(config-if)#switchport trunk encapsulation isl\nSwitch(config-if)#switchport mode trunk" }, { "code": null, "e": 29820, "s": 29603, "text": "In ISL, the original frame is encapsulated and an additional header is added before the frame is carried over a trunk link. At the receiving end, the header is removed and the frame is forwarded to the assigned VLAN." }, { "code": null, "e": 29963, "s": 29820, "text": "ISL supports upto 1000 vlans. The concept of native VLAN is not important for ISL as all frames including the ones for native VLAN are tagged." }, { "code": null, "e": 30183, "s": 29963, "text": "The ISL frame encapsulation is of 30 bytes, 26 byte header, and a 4 byte FCS (frame check sequence) are inserted. Hence a total of 30 Bytes of overhead. Therefore, it is less preferred. Even Cisco advises to use 802.1Q." }, { "code": null, "e": 30204, "s": 30183, "text": "Configuration (ISL):" }, { "code": null, "e": 30328, "s": 30204, "text": "Switch(config)#interface Fa0/1\nSwitch(config-if)#switchport trunk encapsulation isl\nSwitch(config-if)#switchport mode trunk" }, { "code": null, "e": 31447, "s": 30328, "text": "802.1Q –It is IEEE standard method of frame tagging. If user wants to trunk between a Cisco switch link and a different brand switch link, then have to use 802.1Q encapsulation for the trunk to work.In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN.Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan.Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link.Configuration (802.1Q) :Switch(config)#interface Fa 0/1\nSwitch(config-if)#switchport trunk encapsulation 802.1q\nSwitch(config-if)#switchport mode trunk" }, { "code": null, "e": 31714, "s": 31447, "text": "In 802.1Q, the trunking device inserts a 4-byte tag into the original frame and recomputes the frame check sequence (FCS) before the device sends the frame over the trunk link. At the receiving end, the tag is removed and the frame is forwarded to the assigned VLAN." }, { "code": null, "e": 32033, "s": 31714, "text": "Out of 4 bytes, there is a 12 bit VLAN that matters the most. This field tells about the VLAN number to which the frame belongs. The VLAN can vary from 1 to 4094, i.e supported for 4094 VLANs as VLAN 0 4095 are reserved VLANs. 802.1Q supports the concept of native Vlan, i.e the traffic will go untagged for this Vlan." }, { "code": null, "e": 32218, "s": 32033, "text": "Note – Inter-Switch Link (ISL) and 802.1Q are used to provide inter-switch VLAN communication. The ISL or 802.1Q frame tagging is removed if a frame is forwarded out to an access-link." }, { "code": null, "e": 32243, "s": 32218, "text": "Configuration (802.1Q) :" }, { "code": null, "e": 32371, "s": 32243, "text": "Switch(config)#interface Fa 0/1\nSwitch(config-if)#switchport trunk encapsulation 802.1q\nSwitch(config-if)#switchport mode trunk" }, { "code": null, "e": 32388, "s": 32371, "text": "niharikatanwar61" }, { "code": null, "e": 32406, "s": 32388, "text": "Computer Networks" }, { "code": null, "e": 32424, "s": 32406, "text": "Computer Networks" }, { "code": null, "e": 32522, "s": 32424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32556, "s": 32522, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 32599, "s": 32556, "text": "Implementation of Diffie-Hellman Algorithm" }, { "code": null, "e": 32628, "s": 32599, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 32655, "s": 32628, "text": "Socket Programming in Java" }, { "code": null, "e": 32688, "s": 32655, "text": "Hamming Code in Computer Network" }, { "code": null, "e": 32723, "s": 32688, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 32762, "s": 32723, "text": "Distance Vector Routing (DVR) Protocol" }, { "code": null, "e": 32804, "s": 32762, "text": "Types of area networks - LAN, MAN and WAN" }, { "code": null, "e": 32841, "s": 32804, "text": "Error Detection in Computer Networks" } ]
Instant ofEpochSecond() Method in Java with Examples - GeeksforGeeks
15 Oct, 2019 In Instant class, there are two types of ofEpochSecond() method depending upon the parameters passed to it. ofEpochSecond() method of an Instant class used to return an instance of Instant using seconds passed as parameter to method calculated from the epoch of 1970-01-01T00:00:00Z.The nanosecond field is set to zero. Syntax: public static Instant ofEpochSecond(long epochSecond) Parameters: This method accepts only one parameter epochSecond which is the number of seconds from 1970-01-01T00:00:00Z. Return value: This method returns Instant using seconds passed as parameter. Exception: This method throws following Exceptions DateTimeException if the instant exceeds the maximum or minimum instant. Below programs illustrate the ofEpochSecond() method:Program 1: // Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value long epochSecond = 1200000l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond); // print results System.out.println("Instant: " + result); }} Instant: 1970-01-14T21:20:00Z ofEpochSecond() method of an Instant class used to return an instance of Instant using seconds passed as parameter to method calculated from the epoch of 1970-01-01T00:00:00Z and nanoseconds fraction of second is also passed as parameter which will alter the values of the second and nanosecond in order to ensure that the stored nanosecond is in the range 0 to 999, 999, 999. Syntax: public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) Parameters: This method accepts two parameters epochSecond which is the number of seconds from 1970-01-01T00:00:00Z and nanoAdjustment which is the nanosecond adjustment to the number of seconds, positive or negative. Return value: This method returns Instant using seconds passed as parameter. Exception: This method throws following Exceptions: DateTimeException – if the instant exceeds the maximum or minimum instant. ArithmeticException – if numeric overflow occurs. Below programs illustrate the ofEpochSecond() method:Program 1: // Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value and nanoadjustment value long epochSecond = 1200000000l; long nanoadjustment = 999999l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond, nanoadjustment); // print results System.out.println("Instant: " + result); }} Instant: 2008-01-10T21:20:00.000999999Z References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long, long)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long) Akanksha_Rai java-basics Java-Functions Java-Instant Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Different ways of Reading a text file in Java Internal Working of HashMap in Java Introduction to Java Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n15 Oct, 2019" }, { "code": null, "e": 25333, "s": 25225, "text": "In Instant class, there are two types of ofEpochSecond() method depending upon the parameters passed to it." }, { "code": null, "e": 25545, "s": 25333, "text": "ofEpochSecond() method of an Instant class used to return an instance of Instant using seconds passed as parameter to method calculated from the epoch of 1970-01-01T00:00:00Z.The nanosecond field is set to zero." }, { "code": null, "e": 25553, "s": 25545, "text": "Syntax:" }, { "code": null, "e": 25608, "s": 25553, "text": "public static Instant ofEpochSecond(long epochSecond)\n" }, { "code": null, "e": 25729, "s": 25608, "text": "Parameters: This method accepts only one parameter epochSecond which is the number of seconds from 1970-01-01T00:00:00Z." }, { "code": null, "e": 25806, "s": 25729, "text": "Return value: This method returns Instant using seconds passed as parameter." }, { "code": null, "e": 25930, "s": 25806, "text": "Exception: This method throws following Exceptions DateTimeException if the instant exceeds the maximum or minimum instant." }, { "code": null, "e": 25994, "s": 25930, "text": "Below programs illustrate the ofEpochSecond() method:Program 1:" }, { "code": "// Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value long epochSecond = 1200000l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond); // print results System.out.println(\"Instant: \" + result); }}", "e": 26451, "s": 25994, "text": null }, { "code": null, "e": 26482, "s": 26451, "text": "Instant: 1970-01-14T21:20:00Z\n" }, { "code": null, "e": 26859, "s": 26482, "text": "ofEpochSecond() method of an Instant class used to return an instance of Instant using seconds passed as parameter to method calculated from the epoch of 1970-01-01T00:00:00Z and nanoseconds fraction of second is also passed as parameter which will alter the values of the second and nanosecond in order to ensure that the stored nanosecond is in the range 0 to 999, 999, 999." }, { "code": null, "e": 26867, "s": 26859, "text": "Syntax:" }, { "code": null, "e": 26979, "s": 26867, "text": "public static Instant ofEpochSecond(long epochSecond,\n long nanoAdjustment)\n" }, { "code": null, "e": 27197, "s": 26979, "text": "Parameters: This method accepts two parameters epochSecond which is the number of seconds from 1970-01-01T00:00:00Z and nanoAdjustment which is the nanosecond adjustment to the number of seconds, positive or negative." }, { "code": null, "e": 27274, "s": 27197, "text": "Return value: This method returns Instant using seconds passed as parameter." }, { "code": null, "e": 27326, "s": 27274, "text": "Exception: This method throws following Exceptions:" }, { "code": null, "e": 27401, "s": 27326, "text": "DateTimeException – if the instant exceeds the maximum or minimum instant." }, { "code": null, "e": 27451, "s": 27401, "text": "ArithmeticException – if numeric overflow occurs." }, { "code": null, "e": 27515, "s": 27451, "text": "Below programs illustrate the ofEpochSecond() method:Program 1:" }, { "code": "// Java program to demonstrate// Instant.ofEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // long epochsecond value and nanoadjustment value long epochSecond = 1200000000l; long nanoadjustment = 999999l; // apply ofEpochSecond method of Instant class Instant result = Instant.ofEpochSecond(epochSecond, nanoadjustment); // print results System.out.println(\"Instant: \" + result); }}", "e": 28089, "s": 27515, "text": null }, { "code": null, "e": 28130, "s": 28089, "text": "Instant: 2008-01-10T21:20:00.000999999Z\n" }, { "code": null, "e": 28318, "s": 28130, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long, long)https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochSecond(long)" }, { "code": null, "e": 28331, "s": 28318, "text": "Akanksha_Rai" }, { "code": null, "e": 28343, "s": 28331, "text": "java-basics" }, { "code": null, "e": 28358, "s": 28343, "text": "Java-Functions" }, { "code": null, "e": 28371, "s": 28358, "text": "Java-Instant" }, { "code": null, "e": 28389, "s": 28371, "text": "Java-time package" }, { "code": null, "e": 28394, "s": 28389, "text": "Java" }, { "code": null, "e": 28399, "s": 28394, "text": "Java" }, { "code": null, "e": 28497, "s": 28399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28512, "s": 28497, "text": "Stream In Java" }, { "code": null, "e": 28533, "s": 28512, "text": "Constructors in Java" }, { "code": null, "e": 28552, "s": 28533, "text": "Exceptions in Java" }, { "code": null, "e": 28582, "s": 28552, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28599, "s": 28582, "text": "Generics in Java" }, { "code": null, "e": 28645, "s": 28599, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28681, "s": 28645, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 28702, "s": 28681, "text": "Introduction to Java" }, { "code": null, "e": 28745, "s": 28702, "text": "Comparator Interface in Java with Examples" } ]
How to Create a Dynamic Chart Range in Excel? - GeeksforGeeks
01 Jun, 2021 A Dynamic chart range is the range of a data set which automatically updates on any modifications in the original data set. It is beneficial because at some point in time we need to add or delete data from the original data set. So, we want a method to automatically update the chart on performing any modifications in the source data set. This is known as Dynamic Chart Range in which as the source data changes, the dynamic range updates, and within a fraction of seconds the chart associated with the data set automatically gets updated. In this article, we are going to see how to create a dynamic chart range in Excel. Basically, there are two methods : Using the Excel Table made with the data set. Using the Formula method. Let’s consider an example shown below and see how to create a dynamic chart range using the above-listed methods. Example: Consider the data set shown below which consists of the data about the number of students enrolled in our famous courses. We will create a dynamic range so that if any new data are either added or deleted the chart gets modified automatically. This feature is available from Excel 2007 version and higher which we generally use nowadays. It is the most efficient method because when we add new data to the original source table it gets automatically updated. The steps to create a dynamic chart range using a table are as follows : Step 1: Select the table. Step 2: Click on the Insert tab from the top of the Excel window. Step 3: Click on the Table. Step 4: The Create Table window opens. Since the above table has headers “Courses”, “Number of Students” check the box as shown below and then click on OK. The shortcut to the above two steps is CTRL+T which will open the Create Table window directly. Dynamic Range Excel Table Step 5: Now select the entire table and go to Insert and from the Chart Group sets select the 2-D column. You can choose any chart as per requirements. Step 6: Now we insert new data in the Excel table and observe what happens in the chart. It can be observed that as we enter the new data the chart gets automatically updated. It is an alternate method that can be used in any version of Excel. The functions used for generating formulas are “OFFSET”, “COUNTIF”. OFFSET: It is basically used to create a reference offset from a starting point. To create a dynamic range we need the OFFSET function. Syntax: = OFFSET(reference,rows,cols,[height],[width]) arguments : reference,rows,cols,[height],[width] COUNTIF : It is basically used to count cells that match the criteria or a single condition. In criteria, we use LOGICAL OPERATORS like (<,>,>=,<=,<>) and wildcards like (*,?) in case of any partial matching. Syntax: = COUNTIF(range,criteria) arguments : range,criteria Now, let’s discuss the key steps to be followed to create a dynamic range chart. Step 1 : Select any cell in Excel and write the formula as shown below for both “Courses” and “Number of Students”. Copy this formula and store it somewhere, probably a notepad as we need it again. The cell range is taken from Row 3 to Row 102 which is 100 cells in total. So, we created a dynamic range for the user to enter new data into the existing data set. For example : For “The Number of Students” column the cell range will be from B3 to B102. Step 2: Now go to the Formulas tab and select Name Manager. Step 3: Now specify a new name in the Name Manager window. In Refers to: Copy paste the previously written formula for the Number of Students column and click OK. Similarly, do it for the “Courses” column by providing a new name GeekCourses. In this step basically, we are creating two new ranges GeekCourses and GeekStudents which refer to the original data set values. Now, if we add any new data in the previous data set it will automatically be updated in the ranges created in this step. Step 4 : Now we will create a new dynamic chart associated with the Dynamic Range created using the formulas in the above step. Insert a blank chart and then go to the Design tab and click on Select Data. Step 3: The Select Data Source dialog box opens. Now click on Add. In the Series Value enter the following command : Sheet_Name!(Name_Ranged_Formula) Name_Ranged_Formula : The dynamic range created using the Formula. In our case it is : GeekFormula!GeekStudents Now click OK. We can observe that the blank chart is now updated with the data set values. However, the Horizontal-axis (for Courses) is not yet correct. For that, we need go to the Edit tab and write the axis label range as : GeekFormula!GeekCourses Click OK. The Dynamic chart is now ready. Now, enter new data in the original data set and it can be observed that the chart automatically updates. Also, if you delete any data the chart will delete those entries and modifies itself automatically. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Show Percentages in Stacked Column Chart in Excel? How to Extract the Last Word From a Cell in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26313, "s": 26285, "text": "\n01 Jun, 2021" }, { "code": null, "e": 26854, "s": 26313, "text": "A Dynamic chart range is the range of a data set which automatically updates on any modifications in the original data set. It is beneficial because at some point in time we need to add or delete data from the original data set. So, we want a method to automatically update the chart on performing any modifications in the source data set. This is known as Dynamic Chart Range in which as the source data changes, the dynamic range updates, and within a fraction of seconds the chart associated with the data set automatically gets updated." }, { "code": null, "e": 26972, "s": 26854, "text": "In this article, we are going to see how to create a dynamic chart range in Excel. Basically, there are two methods :" }, { "code": null, "e": 27018, "s": 26972, "text": "Using the Excel Table made with the data set." }, { "code": null, "e": 27044, "s": 27018, "text": "Using the Formula method." }, { "code": null, "e": 27158, "s": 27044, "text": "Let’s consider an example shown below and see how to create a dynamic chart range using the above-listed methods." }, { "code": null, "e": 27411, "s": 27158, "text": "Example: Consider the data set shown below which consists of the data about the number of students enrolled in our famous courses. We will create a dynamic range so that if any new data are either added or deleted the chart gets modified automatically." }, { "code": null, "e": 27626, "s": 27411, "text": "This feature is available from Excel 2007 version and higher which we generally use nowadays. It is the most efficient method because when we add new data to the original source table it gets automatically updated." }, { "code": null, "e": 27699, "s": 27626, "text": "The steps to create a dynamic chart range using a table are as follows :" }, { "code": null, "e": 27725, "s": 27699, "text": "Step 1: Select the table." }, { "code": null, "e": 27791, "s": 27725, "text": "Step 2: Click on the Insert tab from the top of the Excel window." }, { "code": null, "e": 27819, "s": 27791, "text": "Step 3: Click on the Table." }, { "code": null, "e": 27975, "s": 27819, "text": "Step 4: The Create Table window opens. Since the above table has headers “Courses”, “Number of Students” check the box as shown below and then click on OK." }, { "code": null, "e": 28071, "s": 27975, "text": "The shortcut to the above two steps is CTRL+T which will open the Create Table window directly." }, { "code": null, "e": 28097, "s": 28071, "text": "Dynamic Range Excel Table" }, { "code": null, "e": 28249, "s": 28097, "text": "Step 5: Now select the entire table and go to Insert and from the Chart Group sets select the 2-D column. You can choose any chart as per requirements." }, { "code": null, "e": 28338, "s": 28249, "text": "Step 6: Now we insert new data in the Excel table and observe what happens in the chart." }, { "code": null, "e": 28426, "s": 28338, "text": "It can be observed that as we enter the new data the chart gets automatically updated. " }, { "code": null, "e": 28562, "s": 28426, "text": "It is an alternate method that can be used in any version of Excel. The functions used for generating formulas are “OFFSET”, “COUNTIF”." }, { "code": null, "e": 28698, "s": 28562, "text": "OFFSET: It is basically used to create a reference offset from a starting point. To create a dynamic range we need the OFFSET function." }, { "code": null, "e": 28706, "s": 28698, "text": "Syntax:" }, { "code": null, "e": 28803, "s": 28706, "text": "= OFFSET(reference,rows,cols,[height],[width])\n\narguments : reference,rows,cols,[height],[width]" }, { "code": null, "e": 29012, "s": 28803, "text": "COUNTIF : It is basically used to count cells that match the criteria or a single condition. In criteria, we use LOGICAL OPERATORS like (<,>,>=,<=,<>) and wildcards like (*,?) in case of any partial matching." }, { "code": null, "e": 29020, "s": 29012, "text": "Syntax:" }, { "code": null, "e": 29074, "s": 29020, "text": "= COUNTIF(range,criteria)\n\narguments : range,criteria" }, { "code": null, "e": 29155, "s": 29074, "text": "Now, let’s discuss the key steps to be followed to create a dynamic range chart." }, { "code": null, "e": 29353, "s": 29155, "text": "Step 1 : Select any cell in Excel and write the formula as shown below for both “Courses” and “Number of Students”. Copy this formula and store it somewhere, probably a notepad as we need it again." }, { "code": null, "e": 29518, "s": 29353, "text": "The cell range is taken from Row 3 to Row 102 which is 100 cells in total. So, we created a dynamic range for the user to enter new data into the existing data set." }, { "code": null, "e": 29608, "s": 29518, "text": "For example : For “The Number of Students” column the cell range will be from B3 to B102." }, { "code": null, "e": 29668, "s": 29608, "text": "Step 2: Now go to the Formulas tab and select Name Manager." }, { "code": null, "e": 29727, "s": 29668, "text": "Step 3: Now specify a new name in the Name Manager window." }, { "code": null, "e": 29831, "s": 29727, "text": "In Refers to: Copy paste the previously written formula for the Number of Students column and click OK." }, { "code": null, "e": 29910, "s": 29831, "text": "Similarly, do it for the “Courses” column by providing a new name GeekCourses." }, { "code": null, "e": 30161, "s": 29910, "text": "In this step basically, we are creating two new ranges GeekCourses and GeekStudents which refer to the original data set values. Now, if we add any new data in the previous data set it will automatically be updated in the ranges created in this step." }, { "code": null, "e": 30289, "s": 30161, "text": "Step 4 : Now we will create a new dynamic chart associated with the Dynamic Range created using the formulas in the above step." }, { "code": null, "e": 30366, "s": 30289, "text": "Insert a blank chart and then go to the Design tab and click on Select Data." }, { "code": null, "e": 30433, "s": 30366, "text": "Step 3: The Select Data Source dialog box opens. Now click on Add." }, { "code": null, "e": 30483, "s": 30433, "text": "In the Series Value enter the following command :" }, { "code": null, "e": 30584, "s": 30483, "text": "Sheet_Name!(Name_Ranged_Formula)\n\nName_Ranged_Formula : The dynamic range created using the Formula." }, { "code": null, "e": 30604, "s": 30584, "text": "In our case it is :" }, { "code": null, "e": 30629, "s": 30604, "text": "GeekFormula!GeekStudents" }, { "code": null, "e": 30856, "s": 30629, "text": "Now click OK. We can observe that the blank chart is now updated with the data set values. However, the Horizontal-axis (for Courses) is not yet correct. For that, we need go to the Edit tab and write the axis label range as :" }, { "code": null, "e": 30880, "s": 30856, "text": "GeekFormula!GeekCourses" }, { "code": null, "e": 30922, "s": 30880, "text": "Click OK. The Dynamic chart is now ready." }, { "code": null, "e": 31128, "s": 30922, "text": "Now, enter new data in the original data set and it can be observed that the chart automatically updates. Also, if you delete any data the chart will delete those entries and modifies itself automatically." }, { "code": null, "e": 31135, "s": 31128, "text": "Picked" }, { "code": null, "e": 31141, "s": 31135, "text": "Excel" }, { "code": null, "e": 31239, "s": 31141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31267, "s": 31239, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 31322, "s": 31267, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 31363, "s": 31322, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 31413, "s": 31363, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 31429, "s": 31413, "text": "Macros in Excel" }, { "code": null, "e": 31463, "s": 31429, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 31521, "s": 31463, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 31572, "s": 31521, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 31628, "s": 31572, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
How to Recover a Deleted File in Linux? - GeeksforGeeks
06 Apr, 2021 We all have often faced a problem where we have accidentally deleted some files in Linux, that we definitely regretted deleting off later on after we did not even found it in the trash. But what if we can recover them? In this article, we will discuss How we can recover a Deleted File in Linux. Whenever we delete something from our system, it does not actually get deleted, till that space gets overwritten by something else in the disk. You can also read about how to securely delete any files permanently. The best way to Recover a Deleted File in Linux is as follows: Unmounting a device immediately after we realize we’ve deleted important files is the best option to prevent the data blocks of the deleted files from being overwritten with other data. At 1st Shut down the system, and do the recovery process by booting from a Live CD/USB Search the partition that contains the file you deleted, for example- /dev/sda1 Recover the file (make sure you have enough space) Sometimes an open file is deleted accidentally, in that case, lsof command is a life-saving command to recover that file. A copy of the file is recreated with the help of lsof command before the file is being closed by the application holding it open. This happens because the inode is still active, so the data blocks are still on the disk until the application holding it open closes it. Step 1: Make a test file inside the /tmp directory touch /tmp/test Step 2: Run something that will hold the file open: tail -f /tmp/test & Note: Here the number is 8561 but in your case, it might be different so use the commands accordingly. Step 3: List the process for confirming the open process ps -ef | grep 8561 | grep -v grep Step 4: Manually just delete the file and try listing the file, you will be shown an error message because it has been deleted $ rm /tmp/test $ ls -l /tmp/test So now we are sure that the file is actually deleted, lets now try to recover it with the help of lsof command Step 5: For displaying the open file descriptor of the process use lsof command $lsof | grep -i test The PID of the process that is holding that file open is displayed in the second column. Step 6: Now we have to locate the open file descriptor in /proc directory $ls -l /proc/8561/fd/3 Step 7: Now the open file (that was deleted but opened by some other process) can be copied back to its original location i.e., under /tmp. After that, you can also rename it by its original name $ cp /proc/8561/fd/3 /tmp/ $mv /tmp/3 /tmp/test $ ls -l /tmp/test Now you are done recovering the file, that you thought to be lost forever. Foremost is a forensic tool that comes more or less pre-installed in kali Linux but if it is not there, you can install it from the command line. The foremost tool is used to recover deleted files from hard disk, memory card, pen drive, etc. This tool uses a process called File Carving for recovering data. For recovering a deleted image use the following command: sudo foremost -v -q -t png -i /dev/sda1 -o ~/test Where /dev/sda1 is the underlying partition where /boot resides. where /home/tithi/Downloads/gg is a directory on a separate disk where the recovered file will be located(don’t recover the files on the same drive where the removed ones were located, it might fail to recover anything). A lot of files will be get recovered together and the recovered name file won’t be similar to the original one. Picked How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26141, "s": 26113, "text": "\n06 Apr, 2021" }, { "code": null, "e": 26437, "s": 26141, "text": "We all have often faced a problem where we have accidentally deleted some files in Linux, that we definitely regretted deleting off later on after we did not even found it in the trash. But what if we can recover them? In this article, we will discuss How we can recover a Deleted File in Linux." }, { "code": null, "e": 26651, "s": 26437, "text": "Whenever we delete something from our system, it does not actually get deleted, till that space gets overwritten by something else in the disk. You can also read about how to securely delete any files permanently." }, { "code": null, "e": 26714, "s": 26651, "text": "The best way to Recover a Deleted File in Linux is as follows:" }, { "code": null, "e": 26901, "s": 26714, "text": "Unmounting a device immediately after we realize we’ve deleted important files is the best option to prevent the data blocks of the deleted files from being overwritten with other data. " }, { "code": null, "e": 26988, "s": 26901, "text": "At 1st Shut down the system, and do the recovery process by booting from a Live CD/USB" }, { "code": null, "e": 27068, "s": 26988, "text": "Search the partition that contains the file you deleted, for example- /dev/sda1" }, { "code": null, "e": 27119, "s": 27068, "text": "Recover the file (make sure you have enough space)" }, { "code": null, "e": 27241, "s": 27119, "text": "Sometimes an open file is deleted accidentally, in that case, lsof command is a life-saving command to recover that file." }, { "code": null, "e": 27510, "s": 27241, "text": "A copy of the file is recreated with the help of lsof command before the file is being closed by the application holding it open. This happens because the inode is still active, so the data blocks are still on the disk until the application holding it open closes it. " }, { "code": null, "e": 27561, "s": 27510, "text": "Step 1: Make a test file inside the /tmp directory" }, { "code": null, "e": 27578, "s": 27561, "text": "touch /tmp/test " }, { "code": null, "e": 27630, "s": 27578, "text": "Step 2: Run something that will hold the file open:" }, { "code": null, "e": 27652, "s": 27630, "text": " tail -f /tmp/test & " }, { "code": null, "e": 27755, "s": 27652, "text": "Note: Here the number is 8561 but in your case, it might be different so use the commands accordingly." }, { "code": null, "e": 27812, "s": 27755, "text": "Step 3: List the process for confirming the open process" }, { "code": null, "e": 27848, "s": 27812, "text": "ps -ef | grep 8561 | grep -v grep " }, { "code": null, "e": 27976, "s": 27848, "text": "Step 4: Manually just delete the file and try listing the file, you will be shown an error message because it has been deleted" }, { "code": null, "e": 28017, "s": 27976, "text": "$ rm /tmp/test \n$ ls -l /tmp/test " }, { "code": null, "e": 28129, "s": 28017, "text": "So now we are sure that the file is actually deleted, lets now try to recover it with the help of lsof command " }, { "code": null, "e": 28209, "s": 28129, "text": "Step 5: For displaying the open file descriptor of the process use lsof command" }, { "code": null, "e": 28231, "s": 28209, "text": "$lsof | grep -i test " }, { "code": null, "e": 28320, "s": 28231, "text": "The PID of the process that is holding that file open is displayed in the second column." }, { "code": null, "e": 28394, "s": 28320, "text": "Step 6: Now we have to locate the open file descriptor in /proc directory" }, { "code": null, "e": 28418, "s": 28394, "text": "$ls -l /proc/8561/fd/3 " }, { "code": null, "e": 28614, "s": 28418, "text": "Step 7: Now the open file (that was deleted but opened by some other process) can be copied back to its original location i.e., under /tmp. After that, you can also rename it by its original name" }, { "code": null, "e": 28739, "s": 28614, "text": "$ cp /proc/8561/fd/3 /tmp/ \n$mv /tmp/3 /tmp/test \n$ ls -l /tmp/test " }, { "code": null, "e": 28814, "s": 28739, "text": "Now you are done recovering the file, that you thought to be lost forever." }, { "code": null, "e": 29056, "s": 28814, "text": "Foremost is a forensic tool that comes more or less pre-installed in kali Linux but if it is not there, you can install it from the command line. The foremost tool is used to recover deleted files from hard disk, memory card, pen drive, etc." }, { "code": null, "e": 29122, "s": 29056, "text": "This tool uses a process called File Carving for recovering data." }, { "code": null, "e": 29180, "s": 29122, "text": "For recovering a deleted image use the following command:" }, { "code": null, "e": 29230, "s": 29180, "text": "sudo foremost -v -q -t png -i /dev/sda1 -o ~/test" }, { "code": null, "e": 29295, "s": 29230, "text": "Where /dev/sda1 is the underlying partition where /boot resides." }, { "code": null, "e": 29628, "s": 29295, "text": "where /home/tithi/Downloads/gg is a directory on a separate disk where the recovered file will be located(don’t recover the files on the same drive where the removed ones were located, it might fail to recover anything). A lot of files will be get recovered together and the recovered name file won’t be similar to the original one." }, { "code": null, "e": 29635, "s": 29628, "text": "Picked" }, { "code": null, "e": 29642, "s": 29635, "text": "How To" }, { "code": null, "e": 29653, "s": 29642, "text": "Linux-Unix" }, { "code": null, "e": 29751, "s": 29653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29785, "s": 29751, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29843, "s": 29785, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29892, "s": 29843, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29939, "s": 29892, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 29981, "s": 29939, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 30021, "s": 29981, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 30061, "s": 30021, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 30088, "s": 30061, "text": "grep command in Unix/Linux" }, { "code": null, "e": 30123, "s": 30088, "text": "cut command in Linux with examples" } ]
List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...) - GeeksforGeeks
18 Sep, 2018 Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()...) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till ‘b’ mentioned in arguments. 2. pop() :- This method deletes the element at the position mentioned in its arguments. # Python code to demonstrate the working of# del and pop() # initializing list lis = [2, 1, 3, 5, 4, 3, 8] # using del to delete elements from pos. 2 to 5# deletes 3,5,4del lis[2 : 5] # displaying list after deleting print ("List elements after deleting are : ",end="")for i in range(0, len(lis)): print(lis[i], end=" ") print("\r") # using pop() to delete element at pos 2# deletes 3lis.pop(2) # displaying list after popping print ("List elements after popping are : ", end="")for i in range(0, len(lis)): print(lis[i], end=" ") Output: List elements after deleting are : 2 1 3 8 List elements after popping are : 2 1 8 3. insert(a, x) :- This function inserts an element at the position mentioned in its arguments. It takes 2 arguments, position and element to be added at respective position. 4. remove() :- This function is used to delete the first occurrence of number mentioned in its arguments. # Python code to demonstrate the working of# insert() and remove() # initializing list lis = [2, 1, 3, 5, 3, 8] # using insert() to insert 4 at 3rd poslis.insert(3, 4) # displaying list after insertingprint("List elements after inserting 4 are : ", end="")for i in range(0, len(lis)): print(lis[i], end=" ") print("\r") # using remove() to remove first occurrence of 3# removes 3 at pos 2lis.remove(3) # displaying list after removing print ("List elements after removing are : ", end="")for i in range(0, len(lis)): print(lis[i], end=" ") Output: List elements after inserting 4 are : 2 1 3 4 5 3 8 List elements after removing are : 2 1 4 5 3 8 5. sort() :- This function sorts the list in increasing order. 6. reverse() :- This function reverses the elements of list. # Python code to demonstrate the working of# sort() and reverse() # initializing list lis = [2, 1, 3, 5, 3, 8] # using sort() to sort the listlis.sort() # displaying list after sortingprint ("List elements after sorting are : ", end="")for i in range(0, len(lis)): print(lis[i], end=" ") print("\r") # using reverse() to reverse the listlis.reverse() # displaying list after reversingprint ("List elements after reversing are : ", end="")for i in range(0, len(lis)): print(lis[i], end=" ") Output: List elements after sorting are : 1 2 3 3 5 8 List elements after reversing are : 8 5 3 3 2 1 7. extend(b) :- This function is used to extend the list with the elements present in another list. This function takes another list as its argument. 8. clear() :- This function is used to erase all the elements of list. After this operation, list becomes empty. # Python code to demonstrate the working of# extend() and clear() # initializing list 1lis1 = [2, 1, 3, 5] # initializing list 1lis2 = [6, 4, 3] # using extend() to add elements of lis2 in lis1lis1.extend(lis2) # displaying list after sortingprint ("List elements after extending are : ", end="")for i in range(0, len(lis1)): print(lis1[i], end=" ") print ("\r") # using clear() to delete all lis1 contentslis1.clear() # displaying list after clearingprint ("List elements after clearing are : ", end="")for i in range(0, len(lis1)): print(lis1[i], end=" ") Output: List elements after extending are : 2 1 3 5 6 4 3 List elements after clearing are : Related articles:List methods in PythonList Methods in Python | Set 1 (in, not in, len(), min(), max()...) This article is contributed by Manjeet Singh .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. python-list python-list-functions Python School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 25565, "s": 25537, "text": "\n18 Sep, 2018" }, { "code": null, "e": 25619, "s": 25565, "text": "Some of the list methods are mentioned in set 1 below" }, { "code": null, "e": 25687, "s": 25619, "text": "List Methods in Python | Set 1 (in, not in, len(), min(), max()...)" }, { "code": null, "e": 25731, "s": 25687, "text": "More methods are discussed in this article." }, { "code": null, "e": 25851, "s": 25731, "text": "1. del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till ‘b’ mentioned in arguments." }, { "code": null, "e": 25939, "s": 25851, "text": "2. pop() :- This method deletes the element at the position mentioned in its arguments." }, { "code": "# Python code to demonstrate the working of# del and pop() # initializing list lis = [2, 1, 3, 5, 4, 3, 8] # using del to delete elements from pos. 2 to 5# deletes 3,5,4del lis[2 : 5] # displaying list after deleting print (\"List elements after deleting are : \",end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \") print(\"\\r\") # using pop() to delete element at pos 2# deletes 3lis.pop(2) # displaying list after popping print (\"List elements after popping are : \", end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \")", "e": 26487, "s": 25939, "text": null }, { "code": null, "e": 26495, "s": 26487, "text": "Output:" }, { "code": null, "e": 26581, "s": 26495, "text": "List elements after deleting are : 2 1 3 8 \nList elements after popping are : 2 1 8 \n" }, { "code": null, "e": 26756, "s": 26581, "text": "3. insert(a, x) :- This function inserts an element at the position mentioned in its arguments. It takes 2 arguments, position and element to be added at respective position." }, { "code": null, "e": 26862, "s": 26756, "text": "4. remove() :- This function is used to delete the first occurrence of number mentioned in its arguments." }, { "code": "# Python code to demonstrate the working of# insert() and remove() # initializing list lis = [2, 1, 3, 5, 3, 8] # using insert() to insert 4 at 3rd poslis.insert(3, 4) # displaying list after insertingprint(\"List elements after inserting 4 are : \", end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \") print(\"\\r\") # using remove() to remove first occurrence of 3# removes 3 at pos 2lis.remove(3) # displaying list after removing print (\"List elements after removing are : \", end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \")", "e": 27418, "s": 26862, "text": null }, { "code": null, "e": 27426, "s": 27418, "text": "Output:" }, { "code": null, "e": 27528, "s": 27426, "text": "List elements after inserting 4 are : 2 1 3 4 5 3 8 \nList elements after removing are : 2 1 4 5 3 8 \n" }, { "code": null, "e": 27591, "s": 27528, "text": "5. sort() :- This function sorts the list in increasing order." }, { "code": null, "e": 27652, "s": 27591, "text": "6. reverse() :- This function reverses the elements of list." }, { "code": "# Python code to demonstrate the working of# sort() and reverse() # initializing list lis = [2, 1, 3, 5, 3, 8] # using sort() to sort the listlis.sort() # displaying list after sortingprint (\"List elements after sorting are : \", end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \") print(\"\\r\") # using reverse() to reverse the listlis.reverse() # displaying list after reversingprint (\"List elements after reversing are : \", end=\"\")for i in range(0, len(lis)): print(lis[i], end=\" \")", "e": 28158, "s": 27652, "text": null }, { "code": null, "e": 28166, "s": 28158, "text": "Output:" }, { "code": null, "e": 28263, "s": 28166, "text": "List elements after sorting are : 1 2 3 3 5 8 \nList elements after reversing are : 8 5 3 3 2 1 \n" }, { "code": null, "e": 28413, "s": 28263, "text": "7. extend(b) :- This function is used to extend the list with the elements present in another list. This function takes another list as its argument." }, { "code": null, "e": 28526, "s": 28413, "text": "8. clear() :- This function is used to erase all the elements of list. After this operation, list becomes empty." }, { "code": "# Python code to demonstrate the working of# extend() and clear() # initializing list 1lis1 = [2, 1, 3, 5] # initializing list 1lis2 = [6, 4, 3] # using extend() to add elements of lis2 in lis1lis1.extend(lis2) # displaying list after sortingprint (\"List elements after extending are : \", end=\"\")for i in range(0, len(lis1)): print(lis1[i], end=\" \") print (\"\\r\") # using clear() to delete all lis1 contentslis1.clear() # displaying list after clearingprint (\"List elements after clearing are : \", end=\"\")for i in range(0, len(lis1)): print(lis1[i], end=\" \")", "e": 29101, "s": 28526, "text": null }, { "code": null, "e": 29109, "s": 29101, "text": "Output:" }, { "code": null, "e": 29197, "s": 29109, "text": "List elements after extending are : 2 1 3 5 6 4 3 \nList elements after clearing are : \n" }, { "code": null, "e": 29304, "s": 29197, "text": "Related articles:List methods in PythonList Methods in Python | Set 1 (in, not in, len(), min(), max()...)" }, { "code": null, "e": 29605, "s": 29304, "text": "This article is contributed by Manjeet Singh .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": 29730, "s": 29605, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29742, "s": 29730, "text": "python-list" }, { "code": null, "e": 29764, "s": 29742, "text": "python-list-functions" }, { "code": null, "e": 29771, "s": 29764, "text": "Python" }, { "code": null, "e": 29790, "s": 29771, "text": "School Programming" }, { "code": null, "e": 29802, "s": 29790, "text": "python-list" }, { "code": null, "e": 29900, "s": 29802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29932, "s": 29900, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29954, "s": 29932, "text": "Enumerate() in Python" }, { "code": null, "e": 29996, "s": 29954, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30022, "s": 29996, "text": "Python String | replace()" }, { "code": null, "e": 30051, "s": 30022, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30067, "s": 30051, "text": "Arrays in C/C++" }, { "code": null, "e": 30086, "s": 30067, "text": "Inheritance in C++" }, { "code": null, "e": 30111, "s": 30086, "text": "Reverse a string in Java" }, { "code": null, "e": 30135, "s": 30111, "text": "C++ Classes and Objects" } ]
Find relative rank of each element in array
21 Aug, 2020 Given an array A[] of N integers, the task is to find the relative rank for each element in the given array. The relative rank for each element in the array is the count of elements which is greater than the current element in the Longest Increasing Subsequence from the current element. Examples: Input: A[] = {8, 16, 5, 6, 9}, N = 5Output: {1, 0, 2, 1, 0}Explanation:For i = 0, required sequence is {8, 16} Relative Rank = 1.For i = 1, Since all elements after 16 are smaller than 16, Relative Rank = 0.For i = 2, required sequence is {5, 6, 9} Relative Rank = 2For i = 3, required sequence is {6, 9} Relative Rank = 1For i = 4, required sequence is {9} Relative Rank = 0 Input: A[] = {1, 2, 3, 5, 4}Output: {3, 2, 1, 0, 0}Explanation:For i = 0, required sequence is {1, 2, 3, 5}, Relative Rank = 3For i = 1, required sequence is {2, 3, 5}, Relative Rank = 2For i = 2, required sequence is {3, 5}, Relative Rank = 1For i = 3, required sequence is {5}, Relative Rank = 0For i = 4, required sequence is {4}, Relative Rank = 0 Naive Approach: The idea is to generate the longest increasing subsequence for each element and then, the relative rank for each element is the (length of LIS – 1). Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to use a Stack and store the elements which in non-decreasing order from the right till each element(say A[i]) then the rank for each A[i] is the (size of stack – 1) till that element. Below is the illustration of the same: 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; // Function to find relative rank for// each element in the array A[]void findRank(int A[], int N){ // Create Rank Array int rank[N] = {}; // Stack to store numbers in // non-decreasing order from right stack<int> s; // Push last element in stack s.push(A[N - 1]); // Iterate from second last // element to first element for (int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.top()) { s.push(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.size() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (!s.empty() && A[i] >= s.top()) { s.pop(); } // Push current element in Stack s.push(A[i]); // Rank is stack size - 1 rank[i] = s.size() - 1; } } // Print rank of all elements for (int i = 0; i < N; i++) { cout << rank[i] << " "; }} // Driver Codeint main(){ // Given array A[] int A[] = { 1, 2, 3, 5, 4 }; int N = sizeof(A) / sizeof(A[0]); // Function call findRank(A, N); return 0;} // Java program to implement// the above approachimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function to find relative rank for// each element in the array A[]static void findRank(int[] A, int N){ // Create Rank Array int[] rank = new int[N]; // Stack to store numbers in // non-decreasing order from right Stack<Integer> s = new Stack<Integer>(); // Push last element in stack s.add(A[N - 1]); // Iterate from second last // element to first element for(int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.peek()) { s.add(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.size() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (!s.isEmpty() && A[i] >= s.peek()) { s.pop(); } // Push current element in Stack s.add(A[i]); // Rank is stack size - 1 rank[i] = s.size() - 1; } } // Print rank of all elements for(int i = 0; i < N; i++) { System.out.print(rank[i] + " "); }} // Driver Codepublic static void main(String[] args){ // Given array A[] int A[] = { 1, 2, 3, 5, 4 }; int N = A.length; // Function call findRank(A, N);}} // This code is contributed by sanjoy_62 # Python3 program for the above approach # Function to find relative rank for# each element in the array A[]def findRank(A, N): # Create Rank Array rank = [0] * N # Stack to store numbers in # non-decreasing order from right s = [] # Push last element in stack s.append(A[N - 1]) # Iterate from second last # element to first element for i in range(N - 2, -1, -1): # If current element is less # than the top of stack and # append A[i] in stack if (A[i] < s[-1]): s.append(A[i]) # Rank is stack size - 1 # for current element rank[i] = len(s) - 1 else: # Pop elements from stack # till current element is # greater than the top while (len(s) > 0 and A[i] >= s[-1]): del s[-1] # Push current element in Stack s.append(A[i]) # Rank is stack size - 1 rank[i] = len(s) - 1 # Print rank of all elements for i in range(N): print(rank[i], end = " ") # Driver Codeif __name__ == '__main__': # Given array A[] A = [ 1, 2, 3, 5, 4 ] N = len(A) # Function call findRank(A, N) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to find relative rank for// each element in the array A[]static void findRank(int[] A, int N){ // Create Rank Array int[] rank = new int[N]; // Stack to store numbers in // non-decreasing order from right Stack<int> s = new Stack<int>(); // Push last element in stack s.Push(A[N - 1]); // Iterate from second last // element to first element for(int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.Peek()) { s.Push(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.Count() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (s.Count() != 0 && A[i] >= s.Peek()) { s.Pop(); } // Push current element in Stack s.Push(A[i]); // Rank is stack size - 1 rank[i] = s.Count() - 1; } } // Print rank of all elements for(int i = 0; i < N; i++) { Console.Write(rank[i] + " "); }} // Driver Codepublic static void Main(){ // Given array A[] int[] A = new int[] { 1, 2, 3, 5, 4 }; int N = A.Length; // Function call findRank(A, N);}} // This code is contributed by sanjoy_62 3 2 1 0 0 Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 sanjoy_62 cpp-stack Arrays Competitive Programming Greedy Stack Arrays Greedy Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Aug, 2020" }, { "code": null, "e": 137, "s": 28, "text": "Given an array A[] of N integers, the task is to find the relative rank for each element in the given array." }, { "code": null, "e": 316, "s": 137, "text": "The relative rank for each element in the array is the count of elements which is greater than the current element in the Longest Increasing Subsequence from the current element." }, { "code": null, "e": 326, "s": 316, "text": "Examples:" }, { "code": null, "e": 702, "s": 326, "text": "Input: A[] = {8, 16, 5, 6, 9}, N = 5Output: {1, 0, 2, 1, 0}Explanation:For i = 0, required sequence is {8, 16} Relative Rank = 1.For i = 1, Since all elements after 16 are smaller than 16, Relative Rank = 0.For i = 2, required sequence is {5, 6, 9} Relative Rank = 2For i = 3, required sequence is {6, 9} Relative Rank = 1For i = 4, required sequence is {9} Relative Rank = 0" }, { "code": null, "e": 1054, "s": 702, "text": "Input: A[] = {1, 2, 3, 5, 4}Output: {3, 2, 1, 0, 0}Explanation:For i = 0, required sequence is {1, 2, 3, 5}, Relative Rank = 3For i = 1, required sequence is {2, 3, 5}, Relative Rank = 2For i = 2, required sequence is {3, 5}, Relative Rank = 1For i = 3, required sequence is {5}, Relative Rank = 0For i = 4, required sequence is {4}, Relative Rank = 0" }, { "code": null, "e": 1219, "s": 1054, "text": "Naive Approach: The idea is to generate the longest increasing subsequence for each element and then, the relative rank for each element is the (length of LIS – 1)." }, { "code": null, "e": 1263, "s": 1219, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 1551, "s": 1263, "text": "Efficient Approach: To optimize the above approach, the idea is to use a Stack and store the elements which in non-decreasing order from the right till each element(say A[i]) then the rank for each A[i] is the (size of stack – 1) till that element. Below is the illustration of the same:" }, { "code": null, "e": 1602, "s": 1551, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1606, "s": 1602, "text": "C++" }, { "code": null, "e": 1611, "s": 1606, "text": "Java" }, { "code": null, "e": 1619, "s": 1611, "text": "Python3" }, { "code": null, "e": 1622, "s": 1619, "text": "C#" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find relative rank for// each element in the array A[]void findRank(int A[], int N){ // Create Rank Array int rank[N] = {}; // Stack to store numbers in // non-decreasing order from right stack<int> s; // Push last element in stack s.push(A[N - 1]); // Iterate from second last // element to first element for (int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.top()) { s.push(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.size() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (!s.empty() && A[i] >= s.top()) { s.pop(); } // Push current element in Stack s.push(A[i]); // Rank is stack size - 1 rank[i] = s.size() - 1; } } // Print rank of all elements for (int i = 0; i < N; i++) { cout << rank[i] << \" \"; }} // Driver Codeint main(){ // Given array A[] int A[] = { 1, 2, 3, 5, 4 }; int N = sizeof(A) / sizeof(A[0]); // Function call findRank(A, N); return 0;}", "e": 3046, "s": 1622, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function to find relative rank for// each element in the array A[]static void findRank(int[] A, int N){ // Create Rank Array int[] rank = new int[N]; // Stack to store numbers in // non-decreasing order from right Stack<Integer> s = new Stack<Integer>(); // Push last element in stack s.add(A[N - 1]); // Iterate from second last // element to first element for(int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.peek()) { s.add(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.size() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (!s.isEmpty() && A[i] >= s.peek()) { s.pop(); } // Push current element in Stack s.add(A[i]); // Rank is stack size - 1 rank[i] = s.size() - 1; } } // Print rank of all elements for(int i = 0; i < N; i++) { System.out.print(rank[i] + \" \"); }} // Driver Codepublic static void main(String[] args){ // Given array A[] int A[] = { 1, 2, 3, 5, 4 }; int N = A.length; // Function call findRank(A, N);}} // This code is contributed by sanjoy_62", "e": 4653, "s": 3046, "text": null }, { "code": "# Python3 program for the above approach # Function to find relative rank for# each element in the array A[]def findRank(A, N): # Create Rank Array rank = [0] * N # Stack to store numbers in # non-decreasing order from right s = [] # Push last element in stack s.append(A[N - 1]) # Iterate from second last # element to first element for i in range(N - 2, -1, -1): # If current element is less # than the top of stack and # append A[i] in stack if (A[i] < s[-1]): s.append(A[i]) # Rank is stack size - 1 # for current element rank[i] = len(s) - 1 else: # Pop elements from stack # till current element is # greater than the top while (len(s) > 0 and A[i] >= s[-1]): del s[-1] # Push current element in Stack s.append(A[i]) # Rank is stack size - 1 rank[i] = len(s) - 1 # Print rank of all elements for i in range(N): print(rank[i], end = \" \") # Driver Codeif __name__ == '__main__': # Given array A[] A = [ 1, 2, 3, 5, 4 ] N = len(A) # Function call findRank(A, N) # This code is contributed by mohit kumar 29", "e": 5946, "s": 4653, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to find relative rank for// each element in the array A[]static void findRank(int[] A, int N){ // Create Rank Array int[] rank = new int[N]; // Stack to store numbers in // non-decreasing order from right Stack<int> s = new Stack<int>(); // Push last element in stack s.Push(A[N - 1]); // Iterate from second last // element to first element for(int i = N - 2; i >= 0; i--) { // If current element is less // than the top of stack and // push A[i] in stack if (A[i] < s.Peek()) { s.Push(A[i]); // Rank is stack size - 1 // for current element rank[i] = s.Count() - 1; } else { // Pop elements from stack // till current element is // greater than the top while (s.Count() != 0 && A[i] >= s.Peek()) { s.Pop(); } // Push current element in Stack s.Push(A[i]); // Rank is stack size - 1 rank[i] = s.Count() - 1; } } // Print rank of all elements for(int i = 0; i < N; i++) { Console.Write(rank[i] + \" \"); }} // Driver Codepublic static void Main(){ // Given array A[] int[] A = new int[] { 1, 2, 3, 5, 4 }; int N = A.Length; // Function call findRank(A, N);}} // This code is contributed by sanjoy_62", "e": 7542, "s": 5946, "text": null }, { "code": null, "e": 7553, "s": 7542, "text": "3 2 1 0 0\n" }, { "code": null, "e": 7596, "s": 7553, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 7611, "s": 7596, "text": "mohit kumar 29" }, { "code": null, "e": 7621, "s": 7611, "text": "sanjoy_62" }, { "code": null, "e": 7631, "s": 7621, "text": "cpp-stack" }, { "code": null, "e": 7638, "s": 7631, "text": "Arrays" }, { "code": null, "e": 7662, "s": 7638, "text": "Competitive Programming" }, { "code": null, "e": 7669, "s": 7662, "text": "Greedy" }, { "code": null, "e": 7675, "s": 7669, "text": "Stack" }, { "code": null, "e": 7682, "s": 7675, "text": "Arrays" }, { "code": null, "e": 7689, "s": 7682, "text": "Greedy" }, { "code": null, "e": 7695, "s": 7689, "text": "Stack" } ]
How to do exception handling in Ajax ?
27 Oct, 2021 The purpose of this article is to demonstrate how do we handle the exception in the jQuery AJAX request. A basic understanding of HTML, CSS, and jQuery is required. This can be done by an AJAX fail() method. We discuss 3 AJAX methods to better understand what’s going on when making any ajax() request from our web browser to a particular server. AJAX: AJAX is an acronym for “Asynchronous JavaScript and XML”. The Ajax component exploits this ability of JavaScript to send asynchronous HTTP requests, receive the XML response (as well as other formats), and update part of a website (using JavaScript) without reloading or refreshing the entire site. The three methods that we need to know to make AJAX requests are as follows. This method is called when an HTTP request is successful. $.ajax(options).done(callback) This method is called when an HTTP request fails. $.ajax(options).fail(callback) This method is called always, be the HTTP request fails or is successful. $.ajax(options).always(callback) Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request. The whole object with values of the different parameters is shown in the text area. The output is shown in JSON format to show you the value and type of the value that is received as a parameter when an HTTP request fails. The format of the output is as follows. "firstparam": { value: -> the value of the first parameter type: -> the type of the first parameter }, "secondparam": { value: -> value of second parameter type: -> the type of the second parameter }, " thirdparam": { value: -> value of third parameter type: -> the type of the third parameter } Example: HTML <!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <style> .container { display: flex; justify-content: center; } h1 { color: green; } textarea { margin-top: 10px; width: 300px; height: 300px; } </style> <script type="text/javascript"> $(document).ready(function () { var obj = ""; $.ajax("gfg.txt").done(function () { alert("success"); }).fail(function (errorobj, textstatus, error) { obj = JSON.stringify({ firstparam: { value: errorobj, type: typeof (errorobj) }, secondparam: { value: textstatus, type: typeof (textstatus) }, thirdparam: { value: error, type: typeof (error) } }, undefined, 1); }).always(function () { $('textarea').val(obj); }); }); </script></head> <body> <h1 class="container"> GeeksforGeeks </h1> <div class="container"> <textarea></textarea> </div></body> </html> Output: CSS-Properties HTML-Questions jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Oct, 2021" }, { "code": null, "e": 376, "s": 28, "text": "The purpose of this article is to demonstrate how do we handle the exception in the jQuery AJAX request. A basic understanding of HTML, CSS, and jQuery is required. This can be done by an AJAX fail() method. We discuss 3 AJAX methods to better understand what’s going on when making any ajax() request from our web browser to a particular server." }, { "code": null, "e": 681, "s": 376, "text": "AJAX: AJAX is an acronym for “Asynchronous JavaScript and XML”. The Ajax component exploits this ability of JavaScript to send asynchronous HTTP requests, receive the XML response (as well as other formats), and update part of a website (using JavaScript) without reloading or refreshing the entire site." }, { "code": null, "e": 758, "s": 681, "text": "The three methods that we need to know to make AJAX requests are as follows." }, { "code": null, "e": 816, "s": 758, "text": "This method is called when an HTTP request is successful." }, { "code": null, "e": 847, "s": 816, "text": "$.ajax(options).done(callback)" }, { "code": null, "e": 897, "s": 847, "text": "This method is called when an HTTP request fails." }, { "code": null, "e": 928, "s": 897, "text": "$.ajax(options).fail(callback)" }, { "code": null, "e": 1002, "s": 928, "text": "This method is called always, be the HTTP request fails or is successful." }, { "code": null, "e": 1035, "s": 1002, "text": "$.ajax(options).always(callback)" }, { "code": null, "e": 1572, "s": 1035, "text": "Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request. The whole object with values of the different parameters is shown in the text area. The output is shown in JSON format to show you the value and type of the value that is received as a parameter when an HTTP request fails." }, { "code": null, "e": 1612, "s": 1572, "text": "The format of the output is as follows." }, { "code": null, "e": 1935, "s": 1612, "text": "\"firstparam\": {\n value: -> the value of the first parameter\n type: -> the type of the first parameter\n},\n\"secondparam\": {\n value: -> value of second parameter\n type: -> the type of the second parameter\n},\n\" thirdparam\": {\n value: -> value of third parameter\n type: -> the type of the third parameter\n}" }, { "code": null, "e": 1944, "s": 1935, "text": "Example:" }, { "code": null, "e": 1949, "s": 1944, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <style> .container { display: flex; justify-content: center; } h1 { color: green; } textarea { margin-top: 10px; width: 300px; height: 300px; } </style> <script type=\"text/javascript\"> $(document).ready(function () { var obj = \"\"; $.ajax(\"gfg.txt\").done(function () { alert(\"success\"); }).fail(function (errorobj, textstatus, error) { obj = JSON.stringify({ firstparam: { value: errorobj, type: typeof (errorobj) }, secondparam: { value: textstatus, type: typeof (textstatus) }, thirdparam: { value: error, type: typeof (error) } }, undefined, 1); }).always(function () { $('textarea').val(obj); }); }); </script></head> <body> <h1 class=\"container\"> GeeksforGeeks </h1> <div class=\"container\"> <textarea></textarea> </div></body> </html>", "e": 3385, "s": 1949, "text": null }, { "code": null, "e": 3393, "s": 3385, "text": "Output:" }, { "code": null, "e": 3408, "s": 3393, "text": "CSS-Properties" }, { "code": null, "e": 3423, "s": 3408, "text": "HTML-Questions" }, { "code": null, "e": 3440, "s": 3423, "text": "jQuery-Questions" }, { "code": null, "e": 3447, "s": 3440, "text": "Picked" }, { "code": null, "e": 3454, "s": 3447, "text": "JQuery" }, { "code": null, "e": 3471, "s": 3454, "text": "Web Technologies" } ]
How to change font color of the active nav-item in Bootstrap ?
08 Sep, 2021 There are two ways that you can change the font color of the active nav-item. The default font-color is white of the active nav-link in the case of Bootstrap nav-active item. The first-way approach is to use a CSS styling file and changing the nav-item class when clicked. The second-way approach is to change the color using jQuery .css() property and also changing the class status to active for a nav-item using jQuery. Approach 1: Providing an Overriding CSS Styling: To change the color of the font an overriding styling file can be added to the HTML file. This style file will be used to change the font-color of the selected nav-item. When a nav-item is selected, this style file will be added to that particular nav-item. Example: html <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"> </script> <title>Active Link using css style</title> <style> /*Code to change color of active link*/ .navbar-nav > .active > a { color: red; } </style> </head> <body> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#"> Home </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> GeeksForGeeks </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Others </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <script> $(document).ready(function () { $("ul.navbar-nav > li").click(function (e) { $("ul.navbar-nav > li").removeClass("active"); $(this).addClass("active"); }); }); </script> </body></html> Output: Here you can observer the color of the active link is changed to red. Home link is clicked and its font-color changed to red GeeksForGeeks nav item is clicked Approach 2: To change font-color of active-nav using jQuery: To change the font-color of the active-nav link using jQuery, we need to add the active class to that particular nav-item and then we just need to apply the .css(property,value) to change the font- color of the active nav-item. Example: html <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"> </script> <title>Active Link font color using jquery</title> </head> <body> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#"> Home </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> GeeksForGeeks </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Others </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <script type="text/javascript"> $(document).ready(function () { $("ul.navbar-nav > li > a").click( function (e) { $("ul.navbar-nav > li").removeClass( "active"); $("ul.navbar-nav > li > a").css( "color", ""); $(this).addClass("active"); $(this).css("color", "red"); }); }); </script> </body></html> Output: The active link color changed to red. Home link is clicked and its font-color changed to red. Here color is changed using jquery. GeeksForGeeks nav item is clicked Note: The Output of both method will be same. When a particular nav-item is clicked it will change the font-color. surindertarika1234 Bootstrap-4 Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? 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": 54, "s": 26, "text": "\n08 Sep, 2021" }, { "code": null, "e": 327, "s": 54, "text": "There are two ways that you can change the font color of the active nav-item. The default font-color is white of the active nav-link in the case of Bootstrap nav-active item. The first-way approach is to use a CSS styling file and changing the nav-item class when clicked." }, { "code": null, "e": 477, "s": 327, "text": "The second-way approach is to change the color using jQuery .css() property and also changing the class status to active for a nav-item using jQuery." }, { "code": null, "e": 784, "s": 477, "text": "Approach 1: Providing an Overriding CSS Styling: To change the color of the font an overriding styling file can be added to the HTML file. This style file will be used to change the font-color of the selected nav-item. When a nav-item is selected, this style file will be added to that particular nav-item." }, { "code": null, "e": 795, "s": 786, "text": "Example:" }, { "code": null, "e": 802, "s": 797, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script> <script src=\"https://npmcdn.com/[email protected]/dist/js/tether.min.js\"> </script> <title>Active Link using css style</title> <style> /*Code to change color of active link*/ .navbar-nav > .active > a { color: red; } </style> </head> <body> <ul class=\"navbar-nav\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> GeeksForGeeks </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Others </a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Disabled</a> </li> </ul> <script> $(document).ready(function () { $(\"ul.navbar-nav > li\").click(function (e) { $(\"ul.navbar-nav > li\").removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script> </body></html>", "e": 2680, "s": 802, "text": null }, { "code": null, "e": 2688, "s": 2680, "text": "Output:" }, { "code": null, "e": 2758, "s": 2688, "text": "Here you can observer the color of the active link is changed to red." }, { "code": null, "e": 2814, "s": 2758, "text": "Home link is clicked and its font-color changed to red" }, { "code": null, "e": 2848, "s": 2814, "text": "GeeksForGeeks nav item is clicked" }, { "code": null, "e": 3138, "s": 2848, "text": "Approach 2: To change font-color of active-nav using jQuery: To change the font-color of the active-nav link using jQuery, we need to add the active class to that particular nav-item and then we just need to apply the .css(property,value) to change the font- color of the active nav-item. " }, { "code": null, "e": 3149, "s": 3140, "text": "Example:" }, { "code": null, "e": 3156, "s": 3151, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script> <script src=\"https://npmcdn.com/[email protected]/dist/js/tether.min.js\"> </script> <title>Active Link font color using jquery</title> </head> <body> <ul class=\"navbar-nav\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> GeeksForGeeks </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Others </a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Disabled</a> </li> </ul> <script type=\"text/javascript\"> $(document).ready(function () { $(\"ul.navbar-nav > li > a\").click( function (e) { $(\"ul.navbar-nav > li\").removeClass( \"active\"); $(\"ul.navbar-nav > li > a\").css( \"color\", \"\"); $(this).addClass(\"active\"); $(this).css(\"color\", \"red\"); }); }); </script> </body></html>", "e": 5100, "s": 3156, "text": null }, { "code": null, "e": 5108, "s": 5100, "text": "Output:" }, { "code": null, "e": 5146, "s": 5108, "text": "The active link color changed to red." }, { "code": null, "e": 5239, "s": 5146, "text": "Home link is clicked and its font-color changed to red. Here color is changed using jquery." }, { "code": null, "e": 5273, "s": 5239, "text": "GeeksForGeeks nav item is clicked" }, { "code": null, "e": 5389, "s": 5273, "text": "Note: The Output of both method will be same. When a particular nav-item is clicked it will change the font-color. " }, { "code": null, "e": 5408, "s": 5389, "text": "surindertarika1234" }, { "code": null, "e": 5420, "s": 5408, "text": "Bootstrap-4" }, { "code": null, "e": 5435, "s": 5420, "text": "Bootstrap-Misc" }, { "code": null, "e": 5445, "s": 5435, "text": "Bootstrap" }, { "code": null, "e": 5462, "s": 5445, "text": "Web Technologies" }, { "code": null, "e": 5560, "s": 5462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5601, "s": 5560, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 5634, "s": 5601, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 5679, "s": 5634, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 5705, "s": 5679, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 5772, "s": 5705, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 5805, "s": 5772, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5867, "s": 5805, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5928, "s": 5867, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5978, "s": 5928, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Tuple Methods
22 Jul, 2021 Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples. The count() method of Tuple returns the number of times the given element appears in the tuple. Syntax: tuple.count(element) Where the element is the element that is to be counted. Example 1: Using the Tuple count() method Python3 # Creating tuplesTuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)Tuple2 = ('python', 'geek', 'python', 'for', 'java', 'python') # count the appearance of 3res = Tuple1.count(3)print('Count of 3 in Tuple1 is:', res) # count the appearance of pythonres = Tuple2.count('python')print('Count of Python in Tuple2 is:', res) Output: Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3 Example 2: Counting tuples and lists as elements in Tuples Python3 # Creating tuplesTuple = (0, 1, (2, 3), (2, 3), 1, [3, 2], 'geeks', (0,)) # count the appearance of (2, 3)res = Tuple.count((2, 3))print('Count of (2, 3) in Tuple is:', res) # count the appearance of [3, 2]res = Tuple.count([3, 2])print('Count of [3, 2] in Tuple is:', res) Output: Count of (2, 3) in Tuple is: 2 Count of [3, 2] in Tuple is: 1 The Index() method returns the first occurrence of the given element from the tuple. Syntax: tuple.index(element, start, end) Parameters: element: The element to be searched. start (Optional): The starting index from where the searching is started end (Optional): The ending index till where the searching is done Note: This method raises a ValueError if the element is not found in the tuple. Example 1: Using Tuple Index() Method Python3 # Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2) # getting the index of 3res = Tuple.index(3)print('First occurrence of 3 is', res) # getting the index of 3 after 4th# indexres = Tuple.index(3, 4)print('First occurrence of 3 after 4th index is:', res) Output: First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5 Example 2: Using Tuple() method when the element is not found Python3 # Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2) # getting the index of 3res = Tuple.index(4) Output: ValueError: tuple.index(x): x not in tuple Note: For more information on Python Tuples refer to Python Tuple Tutorial. python-tuple Python-tuple-functions 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 Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 248, "s": 28, "text": "Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples." }, { "code": null, "e": 344, "s": 248, "text": "The count() method of Tuple returns the number of times the given element appears in the tuple." }, { "code": null, "e": 352, "s": 344, "text": "Syntax:" }, { "code": null, "e": 373, "s": 352, "text": "tuple.count(element)" }, { "code": null, "e": 429, "s": 373, "text": "Where the element is the element that is to be counted." }, { "code": null, "e": 472, "s": 429, "text": "Example 1: Using the Tuple count() method " }, { "code": null, "e": 480, "s": 472, "text": "Python3" }, { "code": "# Creating tuplesTuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)Tuple2 = ('python', 'geek', 'python', 'for', 'java', 'python') # count the appearance of 3res = Tuple1.count(3)print('Count of 3 in Tuple1 is:', res) # count the appearance of pythonres = Tuple2.count('python')print('Count of Python in Tuple2 is:', res)", "e": 799, "s": 480, "text": null }, { "code": null, "e": 807, "s": 799, "text": "Output:" }, { "code": null, "e": 866, "s": 807, "text": "Count of 3 in Tuple1 is: 3\nCount of Python in Tuple2 is: 3" }, { "code": null, "e": 925, "s": 866, "text": "Example 2: Counting tuples and lists as elements in Tuples" }, { "code": null, "e": 933, "s": 925, "text": "Python3" }, { "code": "# Creating tuplesTuple = (0, 1, (2, 3), (2, 3), 1, [3, 2], 'geeks', (0,)) # count the appearance of (2, 3)res = Tuple.count((2, 3))print('Count of (2, 3) in Tuple is:', res) # count the appearance of [3, 2]res = Tuple.count([3, 2])print('Count of [3, 2] in Tuple is:', res)", "e": 1218, "s": 933, "text": null }, { "code": null, "e": 1226, "s": 1218, "text": "Output:" }, { "code": null, "e": 1288, "s": 1226, "text": "Count of (2, 3) in Tuple is: 2\nCount of [3, 2] in Tuple is: 1" }, { "code": null, "e": 1373, "s": 1288, "text": "The Index() method returns the first occurrence of the given element from the tuple." }, { "code": null, "e": 1381, "s": 1373, "text": "Syntax:" }, { "code": null, "e": 1414, "s": 1381, "text": "tuple.index(element, start, end)" }, { "code": null, "e": 1426, "s": 1414, "text": "Parameters:" }, { "code": null, "e": 1463, "s": 1426, "text": "element: The element to be searched." }, { "code": null, "e": 1536, "s": 1463, "text": "start (Optional): The starting index from where the searching is started" }, { "code": null, "e": 1602, "s": 1536, "text": "end (Optional): The ending index till where the searching is done" }, { "code": null, "e": 1682, "s": 1602, "text": "Note: This method raises a ValueError if the element is not found in the tuple." }, { "code": null, "e": 1720, "s": 1682, "text": "Example 1: Using Tuple Index() Method" }, { "code": null, "e": 1728, "s": 1720, "text": "Python3" }, { "code": "# Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2) # getting the index of 3res = Tuple.index(3)print('First occurrence of 3 is', res) # getting the index of 3 after 4th# indexres = Tuple.index(3, 4)print('First occurrence of 3 after 4th index is:', res)", "e": 1986, "s": 1728, "text": null }, { "code": null, "e": 1994, "s": 1986, "text": "Output:" }, { "code": null, "e": 2065, "s": 1994, "text": "First occurrence of 3 is 3\nFirst occurrence of 3 after 4th index is: 5" }, { "code": null, "e": 2127, "s": 2065, "text": "Example 2: Using Tuple() method when the element is not found" }, { "code": null, "e": 2135, "s": 2127, "text": "Python3" }, { "code": "# Creating tuplesTuple = (0, 1, 2, 3, 2, 3, 1, 3, 2) # getting the index of 3res = Tuple.index(4)", "e": 2234, "s": 2135, "text": null }, { "code": null, "e": 2242, "s": 2234, "text": "Output:" }, { "code": null, "e": 2285, "s": 2242, "text": "ValueError: tuple.index(x): x not in tuple" }, { "code": null, "e": 2361, "s": 2285, "text": "Note: For more information on Python Tuples refer to Python Tuple Tutorial." }, { "code": null, "e": 2374, "s": 2361, "text": "python-tuple" }, { "code": null, "e": 2397, "s": 2374, "text": "Python-tuple-functions" }, { "code": null, "e": 2404, "s": 2397, "text": "Python" }, { "code": null, "e": 2502, "s": 2404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2534, "s": 2502, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2561, "s": 2534, "text": "Python Classes and Objects" }, { "code": null, "e": 2582, "s": 2561, "text": "Python OOPs Concepts" }, { "code": null, "e": 2613, "s": 2582, "text": "Python | os.path.join() method" }, { "code": null, "e": 2669, "s": 2613, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2692, "s": 2669, "text": "Introduction To PYTHON" }, { "code": null, "e": 2734, "s": 2692, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2776, "s": 2734, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2815, "s": 2776, "text": "Python | datetime.timedelta() function" } ]
std::string class in C++
06 Jul, 2022 C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. String Char Array Example: CPP // C++ Program to demonstrate the working of// getline(), push_back() and pop_back()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Declaring string string str; // Taking string input using getline() getline(cin, str); // Displaying string cout << "The initial string is : "; cout << str << endl; // Inserting a character str.push_back('s'); // Displaying string cout << "The string after push_back operation is : "; cout << str << endl; // Deleting a character str.pop_back(); // Displaying string cout << "The string after pop_back operation is : "; cout << str << endl; return 0;} Output: The initial string is : geeksforgeek The string after push_back operation is : geeksforgeeks The string after pop_back operation is : geeksforgeek Example: CPP // C++ Program to demonstrate the working of// capacity(), resize() and shrink_to_fit()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing string string str = "geeksforgeeks is for geeks"; // Displaying string cout << "The initial string is : "; cout << str << endl; // Resizing string using resize() str.resize(13); // Displaying string cout << "The string after resize operation is : "; cout << str << endl; // Displaying capacity of string cout << "The capacity of string is : "; cout << str.capacity() << endl; // Displaying length of the string cout << "The length of the string is :" << str.length() << endl; // Decreasing the capacity of string // using shrink_to_fit() str.shrink_to_fit(); // Displaying string cout << "The new capacity after shrinking is : "; cout << str.capacity() << endl; return 0;} The initial string is : geeksforgeeks is for geeks The string after resize operation is : geeksforgeeks The capacity of string is : 26 The length of the string is :13 The new capacity after shrinking is : 15 Example: CPP // C++ Program to demonstrate the working of// begin(), end(), rbegin(), rend()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing string` string str = "geeksforgeeks"; // Declaring iterator std::string::iterator it; // Declaring reverse iterator std::string::reverse_iterator it1; // Displaying string cout << "The string using forward iterators is : "; for (it = str.begin(); it != str.end(); it++) cout << *it; cout << endl; // Displaying reverse string cout << "The reverse string using reverse iterators is " ": "; for (it1 = str.rbegin(); it1 != str.rend(); it1++) cout << *it1; cout << endl; return 0;} The string using forward iterators is : geeksforgeeks The reverse string using reverse iterators is : skeegrofskeeg 4) Manipulating Functions: Example: CPP // C++ Program to demonstrate the working of// copy() and swap()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing 1st string string str1 = "geeksforgeeks is for geeks"; // Declaring 2nd string string str2 = "geeksforgeeks rocks"; // Declaring character array char ch[80]; // using copy() to copy elements into char array // copies "geeksforgeeks" str1.copy(ch, 13, 0); // Displaying char array cout << "The new copied character array is : "; cout << ch << endl; // Displaying strings before swapping cout << "The 1st string before swapping is : "; cout << str1 << endl; cout << "The 2nd string before swapping is : "; cout << str2 << endl; // using swap() to swap string content str1.swap(str2); // Displaying strings after swapping cout << "The 1st string after swapping is : "; cout << str1 << endl; cout << "The 2nd string after swapping is : "; cout << str2 << endl; return 0;} The new copied character array is : geeksforgeeks The 1st string before swapping is : geeksforgeeks is for geeks The 2nd string before swapping is : geeksforgeeks rocks The 1st string after swapping is : geeksforgeeks rocks The 2nd string after swapping is : geeksforgeeks is for geeks Must Read: C++ String Class and its Applications YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3rDp0yOACZQ" 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 Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. Fenrear keshariashwani678 shettykaran21 thepranaygupta as5853535 johnakup02 anshikajain26 surbhikumaridav harsh_shokeen cpp-string cpp-strings-library STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 314, "s": 52, "text": "C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character." }, { "code": null, "e": 321, "s": 314, "text": "String" }, { "code": null, "e": 332, "s": 321, "text": "Char Array" }, { "code": null, "e": 341, "s": 332, "text": "Example:" }, { "code": null, "e": 345, "s": 341, "text": "CPP" }, { "code": "// C++ Program to demonstrate the working of// getline(), push_back() and pop_back()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Declaring string string str; // Taking string input using getline() getline(cin, str); // Displaying string cout << \"The initial string is : \"; cout << str << endl; // Inserting a character str.push_back('s'); // Displaying string cout << \"The string after push_back operation is : \"; cout << str << endl; // Deleting a character str.pop_back(); // Displaying string cout << \"The string after pop_back operation is : \"; cout << str << endl; return 0;}", "e": 1056, "s": 345, "text": null }, { "code": null, "e": 1065, "s": 1056, "text": "Output: " }, { "code": null, "e": 1212, "s": 1065, "text": "The initial string is : geeksforgeek\nThe string after push_back operation is : geeksforgeeks\nThe string after pop_back operation is : geeksforgeek" }, { "code": null, "e": 1221, "s": 1212, "text": "Example:" }, { "code": null, "e": 1225, "s": 1221, "text": "CPP" }, { "code": "// C++ Program to demonstrate the working of// capacity(), resize() and shrink_to_fit()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing string string str = \"geeksforgeeks is for geeks\"; // Displaying string cout << \"The initial string is : \"; cout << str << endl; // Resizing string using resize() str.resize(13); // Displaying string cout << \"The string after resize operation is : \"; cout << str << endl; // Displaying capacity of string cout << \"The capacity of string is : \"; cout << str.capacity() << endl; // Displaying length of the string cout << \"The length of the string is :\" << str.length() << endl; // Decreasing the capacity of string // using shrink_to_fit() str.shrink_to_fit(); // Displaying string cout << \"The new capacity after shrinking is : \"; cout << str.capacity() << endl; return 0;}", "e": 2195, "s": 1225, "text": null }, { "code": null, "e": 2403, "s": 2195, "text": "The initial string is : geeksforgeeks is for geeks\nThe string after resize operation is : geeksforgeeks\nThe capacity of string is : 26\nThe length of the string is :13\nThe new capacity after shrinking is : 15" }, { "code": null, "e": 2412, "s": 2403, "text": "Example:" }, { "code": null, "e": 2416, "s": 2412, "text": "CPP" }, { "code": "// C++ Program to demonstrate the working of// begin(), end(), rbegin(), rend()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing string` string str = \"geeksforgeeks\"; // Declaring iterator std::string::iterator it; // Declaring reverse iterator std::string::reverse_iterator it1; // Displaying string cout << \"The string using forward iterators is : \"; for (it = str.begin(); it != str.end(); it++) cout << *it; cout << endl; // Displaying reverse string cout << \"The reverse string using reverse iterators is \" \": \"; for (it1 = str.rbegin(); it1 != str.rend(); it1++) cout << *it1; cout << endl; return 0;}", "e": 3174, "s": 2416, "text": null }, { "code": null, "e": 3290, "s": 3174, "text": "The string using forward iterators is : geeksforgeeks\nThe reverse string using reverse iterators is : skeegrofskeeg" }, { "code": null, "e": 3317, "s": 3290, "text": "4) Manipulating Functions:" }, { "code": null, "e": 3326, "s": 3317, "text": "Example:" }, { "code": null, "e": 3330, "s": 3326, "text": "CPP" }, { "code": "// C++ Program to demonstrate the working of// copy() and swap()#include <iostream>#include <string> // for string classusing namespace std; // Driver Codeint main(){ // Initializing 1st string string str1 = \"geeksforgeeks is for geeks\"; // Declaring 2nd string string str2 = \"geeksforgeeks rocks\"; // Declaring character array char ch[80]; // using copy() to copy elements into char array // copies \"geeksforgeeks\" str1.copy(ch, 13, 0); // Displaying char array cout << \"The new copied character array is : \"; cout << ch << endl; // Displaying strings before swapping cout << \"The 1st string before swapping is : \"; cout << str1 << endl; cout << \"The 2nd string before swapping is : \"; cout << str2 << endl; // using swap() to swap string content str1.swap(str2); // Displaying strings after swapping cout << \"The 1st string after swapping is : \"; cout << str1 << endl; cout << \"The 2nd string after swapping is : \"; cout << str2 << endl; return 0;}", "e": 4373, "s": 3330, "text": null }, { "code": null, "e": 4659, "s": 4373, "text": "The new copied character array is : geeksforgeeks\nThe 1st string before swapping is : geeksforgeeks is for geeks\nThe 2nd string before swapping is : geeksforgeeks rocks\nThe 1st string after swapping is : geeksforgeeks rocks\nThe 2nd string after swapping is : geeksforgeeks is for geeks" }, { "code": null, "e": 4708, "s": 4659, "text": "Must Read: C++ String Class and its Applications" }, { "code": null, "e": 5000, "s": 4708, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3rDp0yOACZQ\" 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": 5426, "s": 5000, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 5434, "s": 5426, "text": "Fenrear" }, { "code": null, "e": 5452, "s": 5434, "text": "keshariashwani678" }, { "code": null, "e": 5466, "s": 5452, "text": "shettykaran21" }, { "code": null, "e": 5481, "s": 5466, "text": "thepranaygupta" }, { "code": null, "e": 5491, "s": 5481, "text": "as5853535" }, { "code": null, "e": 5502, "s": 5491, "text": "johnakup02" }, { "code": null, "e": 5516, "s": 5502, "text": "anshikajain26" }, { "code": null, "e": 5532, "s": 5516, "text": "surbhikumaridav" }, { "code": null, "e": 5546, "s": 5532, "text": "harsh_shokeen" }, { "code": null, "e": 5557, "s": 5546, "text": "cpp-string" }, { "code": null, "e": 5577, "s": 5557, "text": "cpp-strings-library" }, { "code": null, "e": 5581, "s": 5577, "text": "STL" }, { "code": null, "e": 5592, "s": 5581, "text": "C Language" }, { "code": null, "e": 5596, "s": 5592, "text": "C++" }, { "code": null, "e": 5600, "s": 5596, "text": "STL" }, { "code": null, "e": 5604, "s": 5600, "text": "CPP" } ]
How to change dropdown menu when time is changed ?
24 Jun, 2020 The task is to change the drop-down menu when time is changed. There are two approaches that are discussed below. Approach 1: Use the setTimeOut() method and execute the code of changing menu after some amount of time. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to change dropdown menu when time is changed? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <p id="GFG_UP"></p> <select id="select"> <option value="1">GFG1</option> <option value="2">GFG2</option> <option value="3">GFG3</option> <option value="4">GFG4</option> <option value="5">GFG5</option> </select> <br><br> <button> Click here </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var elUp = document.getElementById("GFG_UP"); var elDown = document.getElementById("GFG_DOWN"); elUp.innerHTML = "Click on the button " + "to change the dropdown list " + "after 4 seconds"; $('button').click(function () { setTimeout( function () { $("#select option[value=1]") .text('GFG_N'); elDown.innerHTML = "Drop-down menu changed"; }, 4000); }) </script></body> </html> Output: Approach 2: Use the Date() method to get the current DateTime object and then declare the other DateTime object whenever the menu will be changed using setSeconds() and getSeconds() method. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to change dropdown menu when time is changed? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <select id="select"> <option value="1">GFG1</option> <option value="2">GFG2</option> <option value="3">GFG3</option> <option value="4">GFG4</option> <option value="5">GFG5</option> </select> <br> <br> <button> Click here </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var elUp = document.getElementById("GFG_UP"); var elDown = document.getElementById("GFG_DOWN"); elUp.innerHTML = "Click on the button to " + "change the dropdown list after " + "5 seconds of current time"; $('button').click(function () { var d1 = new Date(); var d2 = new Date(); d2.setSeconds(d1.getSeconds() + 5); setTimeout( function () { $("#select option[value=1]") .text('GFG_N'); elDown.innerHTML = "Drop-down menu changed"; }, d2 - d1); }) </script></body> </html> Output: JavaScript-Misc Picked CSS HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2020" }, { "code": null, "e": 142, "s": 28, "text": "The task is to change the drop-down menu when time is changed. There are two approaches that are discussed below." }, { "code": null, "e": 247, "s": 142, "text": "Approach 1: Use the setTimeOut() method and execute the code of changing menu after some amount of time." }, { "code": null, "e": 300, "s": 247, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to change dropdown menu when time is changed? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <select id=\"select\"> <option value=\"1\">GFG1</option> <option value=\"2\">GFG2</option> <option value=\"3\">GFG3</option> <option value=\"4\">GFG4</option> <option value=\"5\">GFG5</option> </select> <br><br> <button> Click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var elUp = document.getElementById(\"GFG_UP\"); var elDown = document.getElementById(\"GFG_DOWN\"); elUp.innerHTML = \"Click on the button \" + \"to change the dropdown list \" + \"after 4 seconds\"; $('button').click(function () { setTimeout( function () { $(\"#select option[value=1]\") .text('GFG_N'); elDown.innerHTML = \"Drop-down menu changed\"; }, 4000); }) </script></body> </html>", "e": 1605, "s": 300, "text": null }, { "code": null, "e": 1613, "s": 1605, "text": "Output:" }, { "code": null, "e": 1803, "s": 1613, "text": "Approach 2: Use the Date() method to get the current DateTime object and then declare the other DateTime object whenever the menu will be changed using setSeconds() and getSeconds() method." }, { "code": null, "e": 1856, "s": 1803, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to change dropdown menu when time is changed? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <select id=\"select\"> <option value=\"1\">GFG1</option> <option value=\"2\">GFG2</option> <option value=\"3\">GFG3</option> <option value=\"4\">GFG4</option> <option value=\"5\">GFG5</option> </select> <br> <br> <button> Click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var elUp = document.getElementById(\"GFG_UP\"); var elDown = document.getElementById(\"GFG_DOWN\"); elUp.innerHTML = \"Click on the button to \" + \"change the dropdown list after \" + \"5 seconds of current time\"; $('button').click(function () { var d1 = new Date(); var d2 = new Date(); d2.setSeconds(d1.getSeconds() + 5); setTimeout( function () { $(\"#select option[value=1]\") .text('GFG_N'); elDown.innerHTML = \"Drop-down menu changed\"; }, d2 - d1); }) </script></body> </html>", "e": 3299, "s": 1856, "text": null }, { "code": null, "e": 3307, "s": 3299, "text": "Output:" }, { "code": null, "e": 3323, "s": 3307, "text": "JavaScript-Misc" }, { "code": null, "e": 3330, "s": 3323, "text": "Picked" }, { "code": null, "e": 3334, "s": 3330, "text": "CSS" }, { "code": null, "e": 3339, "s": 3334, "text": "HTML" }, { "code": null, "e": 3350, "s": 3339, "text": "JavaScript" }, { "code": null, "e": 3357, "s": 3350, "text": "JQuery" }, { "code": null, "e": 3374, "s": 3357, "text": "Web Technologies" }, { "code": null, "e": 3401, "s": 3374, "text": "Web technologies Questions" }, { "code": null, "e": 3406, "s": 3401, "text": "HTML" } ]
Transform a string such that it has abcd..z as a subsequence
26 May, 2021 Given a string S of only small English letters. We need to transform the string by making some number of moves (any number of times) to get the string “abcdefghijklmnopqrstuvwxyz” as a subsequence in that string. In one move, you can replace any character of the string to next character in alphabetical order i.e. ‘a’ can be replaced by ‘b’, ‘b’ can be replaced by ‘c’ and so on. Letter ‘z’ cannot be replaced by any character. If it is not possible to get the subsequence out of that string, then print “Not Possible”.Note: Subsequence of a string is the string obtained by deleting some characters at some positions.Examples: Input : aaaaaaaaaaaaaaaaaaaaaaaaaa Output : abcdefghijklmnopqrstuvwxyz Explanation: Second occurrence of letter 'a' will be replaced by 'b', third occurrence of letter 'a' will be first replaced by 'b' and then by 'c' and so on. Input : helloworld Output : Not Possible This problem can be solved using a greedy approach. The idea is to first observe that in a single move we can increment any character to next character only. That is, ‘c’ can be incremented to ‘d’,’e’,’f’ or any character greater than ‘c’. So we will create a variable ch, initially initialized to ‘a’ and by iterating over the string if we find the current character of the string not greater than ch, we’ll replace it with ch and increase the value of ch in alphabetical order. Since ch is initially equal to ‘a’, we’ll find ‘a’, replace it with ch, increment ch to store ‘b’ and move forward in the string, then if we find any character not greater than ‘b’ replace it with ‘b’ and again increment ch to store ‘c’ and move forward in the string. We will repeat these steps until ch reaches ‘z’ or the entire string is processed. If after traversing the whole string, ch does not reach ‘z’ then it is not possible to obtain the required subsequence.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C Plus Plus Program to transform the// given string to contain the required// subsequence#include <bits/stdc++.h>using namespace std; // function to transform string with string// passed as referencebool transformString(string& s){ // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.size() < 26) return false; for (int i = 0; i < s.size(); i++) { // if ch has reached 'z', it means we have // transformed our string such that required // subsequence can be obtained if (int(ch) > int('z')) break; // current character is not greater than ch, // then replace it with ch and increment ch if (s[i] <= ch) { s[i] = ch; ch = char(int(ch) + 1); } } if (ch <= 'z') return false; return true;} // Driver Codeint main(){ string str = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; if (transformString(str)) cout << str << endl; else cout << "Not Possible" << endl; return 0;} // Java Program to transform the given string// to contain the required subsequenceimport java.io.*; public class GFG { // function to transform string with // string passed as reference static boolean transformString(StringBuilder s) { // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.length() < 26) return false; for (int i = 0; i < s.length(); i++) { // if ch has reached 'z', it means // we have transformed our string // such that required subsequence // can be obtained if ((int)ch > (int)'z') break; // current character is not greater // than ch, then replace it with // ch and increment ch if (s.charAt(i) <= ch) { s.setCharAt(i, ch); ch = (char)((int)ch + 1); } } if (ch <= 'z') return false; return true; } // Driver Code public static void main(String args[]) { StringBuilder str = new StringBuilder("aaaaaaaaaaaaaaaaaaaaaaaaaa"); if (transformString(str)) System.out.println(str.toString()); else System.out.println("Not Possible"); }} // This code is contributed by Manish Shaw// (manishshaw1) # Python3 Program to transform the# given string to contain the required# subsequence # function to transform string with string# passed as referencedef transformString(s) : # initializing the variable ch to 'a' ch = 'a' # if the length of string is less than # 26, we can't obtain the required # subsequence if (len(s) < 26) : return False for i in range(0, len(s)): # if ch has reached 'z', it means we have # transformed our string such that required # subsequence can be obtained if (ord(ch) > ord('z')) : break # current character is not greater than ch, # then replace it with ch and increment ch if (s[i] <= ch) : s[i] = ch ch = chr(ord(ch) + 1) if (ch <= 'z') : print ("Not Possible") print ("".join(s)) # Driver Codes = list("aaaaaaaaaaaaaaaaaaaaaaaaaa")transformString(s) # This code is contributed by Manish Shaw# (manishshaw1) // C# Program to transform the given string// to contain the required subsequenceusing System;using System.Text;using System.Collections.Generic; class GFG { // function to transform string with string // passed as reference static bool transformString(ref StringBuilder s) { // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.Length < 26) return false; for (int i = 0; i < s.Length; i++) { // if ch has reached 'z', it means we // have transformed our string such // that required subsequence can be // obtained if ((int)ch > 122) break; // current character is not greater // than ch, then replace it with ch // and increment ch if (s[i] <= ch) { s[i] = ch; ch = (char)((int)ch + 1); } } if (ch <= 'z') return false; return true; } // Driver Code public static void Main() { StringBuilder str = new StringBuilder("aaaaaaaaaaaaaaaaaaaaaaaaaa"); if (transformString(ref str)) Console.WriteLine(str + "\n"); else Console.WriteLine("Not Possible" + "\n"); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP Program to transform the// given string to contain the required// subsequence // function to transform string with// string passed as referencefunction transformString(&$s){ // initializing the variable // ch to 'a' $ch = "a"; // if the length of string is less than // 26, we can't obtain the required // subsequence if (strlen($s) < 26) return false; for ($i = 0; $i < strlen($s); $i++) { // if ch has reached 'z', // it means we have // transformed our string // such that required // subsequence can be obtained if (ord($ch) > ord("z")) break; // current character is not // greater than ch, then // replace it with ch and // increment ch if ($s[$i] <= $ch) { $s[$i] = $ch; $ch = chr(ord($ch) + 1); } } if ($ch <= "z") return false; return true;} // Driver Code$str = "aaaaaaaaaaaaaaaaaaaaaaaaaa";if (transformString($str)) echo $str;else echo "Not Possible"; // This code is contributed by// Manish Shaw (manishshaw1)?> <script> // Javascript Plus Plus Program to transform the// given string to contain the required// subsequence // function to transform string with string// passed as referencefunction transformString(){ // initializing the variable ch to 'a' var ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.length < 26) return false; for (var i = 0; i < s.length; i++) { // if ch has reached 'z', it means we have // transformed our string such that required // subsequence can be obtained if (ch.charCodeAt(0) > 122) break; // current character is not greater than ch, // then replace it with ch and increment ch if (s[i].charCodeAt(0) <= ch.charCodeAt(0)) { s[i] = ch; ch = String.fromCharCode(ch.charCodeAt(0) + 1); } } s = s.join('') if (ch.charCodeAt(0) <= 'z'.charCodeAt(0)) return false; return true;} // Driver Codevar s = "aaaaaaaaaaaaaaaaaaaaaaaaaa".split(''); if (transformString(s)) document.write(s);else document.write( "Not Possible"); </script> Output: abcdefghijklmnopqrstuvwxyz Time Complexity: O(n), where n is the length of the string. manishshaw1 ManasChhabra2 itsok subsequence Strings Technical Scripter Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2021" }, { "code": null, "e": 683, "s": 52, "text": "Given a string S of only small English letters. We need to transform the string by making some number of moves (any number of times) to get the string “abcdefghijklmnopqrstuvwxyz” as a subsequence in that string. In one move, you can replace any character of the string to next character in alphabetical order i.e. ‘a’ can be replaced by ‘b’, ‘b’ can be replaced by ‘c’ and so on. Letter ‘z’ cannot be replaced by any character. If it is not possible to get the subsequence out of that string, then print “Not Possible”.Note: Subsequence of a string is the string obtained by deleting some characters at some positions.Examples: " }, { "code": null, "e": 956, "s": 683, "text": "Input : aaaaaaaaaaaaaaaaaaaaaaaaaa\nOutput : abcdefghijklmnopqrstuvwxyz\nExplanation: Second occurrence of letter 'a' will be \nreplaced by 'b', third occurrence of letter 'a' will \nbe first replaced by 'b' and then by 'c' and so on.\n\nInput : helloworld\nOutput : Not Possible" }, { "code": null, "e": 1962, "s": 958, "text": "This problem can be solved using a greedy approach. The idea is to first observe that in a single move we can increment any character to next character only. That is, ‘c’ can be incremented to ‘d’,’e’,’f’ or any character greater than ‘c’. So we will create a variable ch, initially initialized to ‘a’ and by iterating over the string if we find the current character of the string not greater than ch, we’ll replace it with ch and increase the value of ch in alphabetical order. Since ch is initially equal to ‘a’, we’ll find ‘a’, replace it with ch, increment ch to store ‘b’ and move forward in the string, then if we find any character not greater than ‘b’ replace it with ‘b’ and again increment ch to store ‘c’ and move forward in the string. We will repeat these steps until ch reaches ‘z’ or the entire string is processed. If after traversing the whole string, ch does not reach ‘z’ then it is not possible to obtain the required subsequence.Below is the implementation of the above approach. " }, { "code": null, "e": 1966, "s": 1962, "text": "C++" }, { "code": null, "e": 1971, "s": 1966, "text": "Java" }, { "code": null, "e": 1979, "s": 1971, "text": "Python3" }, { "code": null, "e": 1982, "s": 1979, "text": "C#" }, { "code": null, "e": 1986, "s": 1982, "text": "PHP" }, { "code": null, "e": 1997, "s": 1986, "text": "Javascript" }, { "code": "// C Plus Plus Program to transform the// given string to contain the required// subsequence#include <bits/stdc++.h>using namespace std; // function to transform string with string// passed as referencebool transformString(string& s){ // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.size() < 26) return false; for (int i = 0; i < s.size(); i++) { // if ch has reached 'z', it means we have // transformed our string such that required // subsequence can be obtained if (int(ch) > int('z')) break; // current character is not greater than ch, // then replace it with ch and increment ch if (s[i] <= ch) { s[i] = ch; ch = char(int(ch) + 1); } } if (ch <= 'z') return false; return true;} // Driver Codeint main(){ string str = \"aaaaaaaaaaaaaaaaaaaaaaaaaa\"; if (transformString(str)) cout << str << endl; else cout << \"Not Possible\" << endl; return 0;}", "e": 3124, "s": 1997, "text": null }, { "code": "// Java Program to transform the given string// to contain the required subsequenceimport java.io.*; public class GFG { // function to transform string with // string passed as reference static boolean transformString(StringBuilder s) { // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.length() < 26) return false; for (int i = 0; i < s.length(); i++) { // if ch has reached 'z', it means // we have transformed our string // such that required subsequence // can be obtained if ((int)ch > (int)'z') break; // current character is not greater // than ch, then replace it with // ch and increment ch if (s.charAt(i) <= ch) { s.setCharAt(i, ch); ch = (char)((int)ch + 1); } } if (ch <= 'z') return false; return true; } // Driver Code public static void main(String args[]) { StringBuilder str = new StringBuilder(\"aaaaaaaaaaaaaaaaaaaaaaaaaa\"); if (transformString(str)) System.out.println(str.toString()); else System.out.println(\"Not Possible\"); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 4616, "s": 3124, "text": null }, { "code": "# Python3 Program to transform the# given string to contain the required# subsequence # function to transform string with string# passed as referencedef transformString(s) : # initializing the variable ch to 'a' ch = 'a' # if the length of string is less than # 26, we can't obtain the required # subsequence if (len(s) < 26) : return False for i in range(0, len(s)): # if ch has reached 'z', it means we have # transformed our string such that required # subsequence can be obtained if (ord(ch) > ord('z')) : break # current character is not greater than ch, # then replace it with ch and increment ch if (s[i] <= ch) : s[i] = ch ch = chr(ord(ch) + 1) if (ch <= 'z') : print (\"Not Possible\") print (\"\".join(s)) # Driver Codes = list(\"aaaaaaaaaaaaaaaaaaaaaaaaaa\")transformString(s) # This code is contributed by Manish Shaw# (manishshaw1)", "e": 5604, "s": 4616, "text": null }, { "code": "// C# Program to transform the given string// to contain the required subsequenceusing System;using System.Text;using System.Collections.Generic; class GFG { // function to transform string with string // passed as reference static bool transformString(ref StringBuilder s) { // initializing the variable ch to 'a' char ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.Length < 26) return false; for (int i = 0; i < s.Length; i++) { // if ch has reached 'z', it means we // have transformed our string such // that required subsequence can be // obtained if ((int)ch > 122) break; // current character is not greater // than ch, then replace it with ch // and increment ch if (s[i] <= ch) { s[i] = ch; ch = (char)((int)ch + 1); } } if (ch <= 'z') return false; return true; } // Driver Code public static void Main() { StringBuilder str = new StringBuilder(\"aaaaaaaaaaaaaaaaaaaaaaaaaa\"); if (transformString(ref str)) Console.WriteLine(str + \"\\n\"); else Console.WriteLine(\"Not Possible\" + \"\\n\"); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 7093, "s": 5604, "text": null }, { "code": "<?php// PHP Program to transform the// given string to contain the required// subsequence // function to transform string with// string passed as referencefunction transformString(&$s){ // initializing the variable // ch to 'a' $ch = \"a\"; // if the length of string is less than // 26, we can't obtain the required // subsequence if (strlen($s) < 26) return false; for ($i = 0; $i < strlen($s); $i++) { // if ch has reached 'z', // it means we have // transformed our string // such that required // subsequence can be obtained if (ord($ch) > ord(\"z\")) break; // current character is not // greater than ch, then // replace it with ch and // increment ch if ($s[$i] <= $ch) { $s[$i] = $ch; $ch = chr(ord($ch) + 1); } } if ($ch <= \"z\") return false; return true;} // Driver Code$str = \"aaaaaaaaaaaaaaaaaaaaaaaaaa\";if (transformString($str)) echo $str;else echo \"Not Possible\"; // This code is contributed by// Manish Shaw (manishshaw1)?>", "e": 8228, "s": 7093, "text": null }, { "code": "<script> // Javascript Plus Plus Program to transform the// given string to contain the required// subsequence // function to transform string with string// passed as referencefunction transformString(){ // initializing the variable ch to 'a' var ch = 'a'; // if the length of string is less than // 26, we can't obtain the required // subsequence if (s.length < 26) return false; for (var i = 0; i < s.length; i++) { // if ch has reached 'z', it means we have // transformed our string such that required // subsequence can be obtained if (ch.charCodeAt(0) > 122) break; // current character is not greater than ch, // then replace it with ch and increment ch if (s[i].charCodeAt(0) <= ch.charCodeAt(0)) { s[i] = ch; ch = String.fromCharCode(ch.charCodeAt(0) + 1); } } s = s.join('') if (ch.charCodeAt(0) <= 'z'.charCodeAt(0)) return false; return true;} // Driver Codevar s = \"aaaaaaaaaaaaaaaaaaaaaaaaaa\".split(''); if (transformString(s)) document.write(s);else document.write( \"Not Possible\"); </script>", "e": 9387, "s": 8228, "text": null }, { "code": null, "e": 9397, "s": 9387, "text": "Output: " }, { "code": null, "e": 9424, "s": 9397, "text": "abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 9485, "s": 9424, "text": "Time Complexity: O(n), where n is the length of the string. " }, { "code": null, "e": 9497, "s": 9485, "text": "manishshaw1" }, { "code": null, "e": 9511, "s": 9497, "text": "ManasChhabra2" }, { "code": null, "e": 9517, "s": 9511, "text": "itsok" }, { "code": null, "e": 9529, "s": 9517, "text": "subsequence" }, { "code": null, "e": 9537, "s": 9529, "text": "Strings" }, { "code": null, "e": 9556, "s": 9537, "text": "Technical Scripter" }, { "code": null, "e": 9564, "s": 9556, "text": "Strings" } ]
Python | Add similar value multiple times in list
30 Dec, 2018 Adding a single value in list is quite generic and easy. But to add that value more than one time, generally, a loop is used to execute this task. Having shorter tricks to perform this can be handy. Let’s discuss certain ways in which this can be done. Method #1 : Using * operatorWe can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable. # Python3 code to demonstrate # to add multiple similar values# using * operator # using * operator to add multiple values# adds 3, 50 times.res = [3] * 50 # printing resultprint ("The filtered list is : " + str(res)) Output : The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] Method #2 : Using extend() + list comprehensionextend function is used to perform the list append and list comprehension part is responsible for performing the task of repetition of elements desired number of times. # Python3 code to demonstrate # to add multiple similar values# using extend() + list comprehension # using extend() + list comprehension to add multiple values# adds 3, 50 times.res = []res.extend([3 for i in range(50)]) # printing resultprint ("The filtered list is : " + str(res)) Output : The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] Method #3 : Using extend() + itertools.repeat()This is similar to the above method, the task of extend() is similar, but repeat() performs the task list comprehension performed of iteration N no. of times desired. # Python3 code to demonstrate # to add multiple similar values# using extend() + itertools.repeat()from itertools import repeat # using extend() + itertools.repeat() to add multiple values# adds 3, 50 times.res = []res.extend(repeat(3, 50)) # printing resultprint ("The filtered list is : " + str(res)) Output : The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2018" }, { "code": null, "e": 281, "s": 28, "text": "Adding a single value in list is quite generic and easy. But to add that value more than one time, generally, a loop is used to execute this task. Having shorter tricks to perform this can be handy. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 504, "s": 281, "text": "Method #1 : Using * operatorWe can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable." }, { "code": "# Python3 code to demonstrate # to add multiple similar values# using * operator # using * operator to add multiple values# adds 3, 50 times.res = [3] * 50 # printing resultprint (\"The filtered list is : \" + str(res))", "e": 724, "s": 504, "text": null }, { "code": null, "e": 733, "s": 724, "text": "Output :" }, { "code": null, "e": 907, "s": 733, "text": "The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]" }, { "code": null, "e": 1123, "s": 907, "text": "Method #2 : Using extend() + list comprehensionextend function is used to perform the list append and list comprehension part is responsible for performing the task of repetition of elements desired number of times." }, { "code": "# Python3 code to demonstrate # to add multiple similar values# using extend() + list comprehension # using extend() + list comprehension to add multiple values# adds 3, 50 times.res = []res.extend([3 for i in range(50)]) # printing resultprint (\"The filtered list is : \" + str(res))", "e": 1409, "s": 1123, "text": null }, { "code": null, "e": 1418, "s": 1409, "text": "Output :" }, { "code": null, "e": 1592, "s": 1418, "text": "The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]" }, { "code": null, "e": 1806, "s": 1592, "text": "Method #3 : Using extend() + itertools.repeat()This is similar to the above method, the task of extend() is similar, but repeat() performs the task list comprehension performed of iteration N no. of times desired." }, { "code": "# Python3 code to demonstrate # to add multiple similar values# using extend() + itertools.repeat()from itertools import repeat # using extend() + itertools.repeat() to add multiple values# adds 3, 50 times.res = []res.extend(repeat(3, 50)) # printing resultprint (\"The filtered list is : \" + str(res))", "e": 2111, "s": 1806, "text": null }, { "code": null, "e": 2120, "s": 2111, "text": "Output :" }, { "code": null, "e": 2294, "s": 2120, "text": "The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]" }, { "code": null, "e": 2315, "s": 2294, "text": "Python list-programs" }, { "code": null, "e": 2322, "s": 2315, "text": "Python" }, { "code": null, "e": 2338, "s": 2322, "text": "Python Programs" }, { "code": null, "e": 2436, "s": 2338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2454, "s": 2436, "text": "Python Dictionary" }, { "code": null, "e": 2496, "s": 2454, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2531, "s": 2496, "text": "Read a file line by line in Python" }, { "code": null, "e": 2557, "s": 2531, "text": "Python String | replace()" }, { "code": null, "e": 2589, "s": 2557, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2632, "s": 2589, "text": "Python program to convert a list to string" }, { "code": null, "e": 2654, "s": 2632, "text": "Defaultdict in Python" }, { "code": null, "e": 2693, "s": 2654, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2731, "s": 2693, "text": "Python | Convert a list to dictionary" } ]
Scala For Comprehensions
19 May, 2019 Comprehensions have the structure for (enumerators) yield e, wherever enumerators refers to a semicolon-separated list of enumerators. Enumerator is either a generator that introduces new variables, or it’s a filter. A comprehension evaluates the body e for every binding generated by the enumerators and returns a sequence of those values. These definitions lead us to the for comprehension ideas of generators, filters, and definitions. A Scala for comprehension will contain the subsequent 3 expressions: Generators Filters Definitions Syntax: for { b <- books // generator n = b.name // definition if (n startsWith "To") // filter } yield Generators -Generators have below form: pattern <- expression For example b <- books In this expression the value b iterates over all of the elements contained in books.Below are two more things about generators - Each for comprehension begins with a generator. for comprehensions will be multiple generators. Definitions - For comprehension definitions have below syntax: pattern = expression For example n = b.name the variable n is bound to the value b.name. That statement has a similar result as writing this code outside of a for comprehension. val n = b.name Filters - For comprehension filters have below form: if (expression) Expression have the type Boolean. Filters drop all elements from the iteration that which expression returns false, as like given code. For example if (n startsWith "Ca") any value n that does not start with the string Ca will be dropped during the iteration process. Let's discuss some examples. Example #1: With yield // Scala program of for comprehensions // Creating object object Geeks { // Main method def main(args: Array[String]) { // Creating case class case class Language(name: String, article: Int) val LanguageBase = List(Language("Scala", 26), Language("Csharp", 32), Language("Perl", 42), Language("Java", 22)) // Applying for comprehensions // Generator // Definition val MoreThanTwenty = for (language <- LanguageBase if (language.article >=20 && language.article < 30))// Filters // i.e. add this to a list yield language.name // Print more than twenty MoreThanTwenty.foreach(name => println(name)) } } Output : Scala Java In above example, the for loop used with a yield statement actually creates a List. Because we said yield language.name, it’s a List[String]. language <- LanguageBase is our generator and if (language.article >=20 && language.article < 30) could be a guard that filters out article those don't seem to be in between 20 to 30. Example #2: Without yield We can omit yield in comprehension. In that case, comprehension will return Unit. This can be helpful just in case we would like to perform side-effects. Here’s a program like the above one, without using yield. // Scala program to print Hello, Geeks! // by using object-oriented approach // creating object object Geeks { // Main method def main(args: Array[String]) { def check(a: Int) = for (i <- 0 until 4; j <- 0 until 4 if i * j >= a) println(s"($i, $j)") check(4)} } Output: (2, 2) (2, 3) (3, 2) (3, 3) In above example, a = 4. In the first iteration, i = 0 and j = 0 so i * j is not greater than equal to a and therefore nothing is yielded. j gets incremented 3 more times before i gets incremented to 1. Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Map Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Operators in Scala Scala | Arrays Scala Constructors How to Install Scala with VSCode?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2019" }, { "code": null, "e": 369, "s": 28, "text": "Comprehensions have the structure for (enumerators) yield e, wherever enumerators refers to a semicolon-separated list of enumerators. Enumerator is either a generator that introduces new variables, or it’s a filter. A comprehension evaluates the body e for every binding generated by the enumerators and returns a sequence of those values." }, { "code": null, "e": 536, "s": 369, "text": "These definitions lead us to the for comprehension ideas of generators, filters, and definitions. A Scala for comprehension will contain the subsequent 3 expressions:" }, { "code": null, "e": 547, "s": 536, "text": "Generators" }, { "code": null, "e": 555, "s": 547, "text": "Filters" }, { "code": null, "e": 567, "s": 555, "text": "Definitions" }, { "code": null, "e": 575, "s": 567, "text": "Syntax:" }, { "code": null, "e": 712, "s": 575, "text": "for {\n b <- books // generator\n n = b.name // definition\n if (n startsWith \"To\") // filter\n} yield\n" }, { "code": null, "e": 753, "s": 712, "text": " Generators -Generators have below form:" }, { "code": null, "e": 775, "s": 753, "text": "pattern <- expression" }, { "code": null, "e": 927, "s": 775, "text": "For example b <- books In this expression the value b iterates over all of the elements contained in books.Below are two more things about generators -" }, { "code": null, "e": 975, "s": 927, "text": "Each for comprehension begins with a generator." }, { "code": null, "e": 1023, "s": 975, "text": "for comprehensions will be multiple generators." }, { "code": null, "e": 1037, "s": 1023, "text": "Definitions -" }, { "code": null, "e": 1086, "s": 1037, "text": "For comprehension definitions have below syntax:" }, { "code": null, "e": 1107, "s": 1086, "text": "pattern = expression" }, { "code": null, "e": 1279, "s": 1107, "text": "For example n = b.name the variable n is bound to the value b.name. That statement has a similar result as writing this code outside of a for comprehension. val n = b.name" }, { "code": null, "e": 1289, "s": 1279, "text": "Filters -" }, { "code": null, "e": 1332, "s": 1289, "text": "For comprehension filters have below form:" }, { "code": null, "e": 1348, "s": 1332, "text": "if (expression)" }, { "code": null, "e": 1616, "s": 1348, "text": "Expression have the type Boolean. Filters drop all elements from the iteration that which expression returns false, as like given code. For example if (n startsWith \"Ca\") any value n that does not start with the string Ca will be dropped during the iteration process." }, { "code": null, "e": 1645, "s": 1616, "text": "Let's discuss some examples." }, { "code": null, "e": 1668, "s": 1645, "text": "Example #1: With yield" }, { "code": "// Scala program of for comprehensions // Creating object object Geeks { // Main method def main(args: Array[String]) { // Creating case class case class Language(name: String, article: Int) val LanguageBase = List(Language(\"Scala\", 26), Language(\"Csharp\", 32), Language(\"Perl\", 42), Language(\"Java\", 22)) // Applying for comprehensions // Generator // Definition val MoreThanTwenty = for (language <- LanguageBase if (language.article >=20 && language.article < 30))// Filters // i.e. add this to a list yield language.name // Print more than twenty MoreThanTwenty.foreach(name => println(name)) } } ", "e": 2521, "s": 1668, "text": null }, { "code": null, "e": 2530, "s": 2521, "text": "Output :" }, { "code": null, "e": 2541, "s": 2530, "text": "Scala\nJava" }, { "code": null, "e": 2893, "s": 2541, "text": "In above example, the for loop used with a yield statement actually creates a List. Because we said yield language.name, it’s a List[String]. language <- LanguageBase is our generator and if (language.article >=20 && language.article < 30) could be a guard that filters out article those don't seem to be in between 20 to 30. Example #2: Without yield" }, { "code": null, "e": 3105, "s": 2893, "text": "We can omit yield in comprehension. In that case, comprehension will return Unit. This can be helpful just in case we would like to perform side-effects. Here’s a program like the above one, without using yield." }, { "code": "// Scala program to print Hello, Geeks! // by using object-oriented approach // creating object object Geeks { // Main method def main(args: Array[String]) { def check(a: Int) = for (i <- 0 until 4; j <- 0 until 4 if i * j >= a) println(s\"($i, $j)\") check(4)} } ", "e": 3390, "s": 3105, "text": null }, { "code": null, "e": 3398, "s": 3390, "text": "Output:" }, { "code": null, "e": 3426, "s": 3398, "text": "(2, 2)\n(2, 3)\n(3, 2)\n(3, 3)" }, { "code": null, "e": 3629, "s": 3426, "text": "In above example, a = 4. In the first iteration, i = 0 and j = 0 so i * j is not greater than equal to a and therefore nothing is yielded. j gets incremented 3 more times before i gets incremented to 1." }, { "code": null, "e": 3635, "s": 3629, "text": "Scala" }, { "code": null, "e": 3733, "s": 3635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3755, "s": 3733, "text": "Type Casting in Scala" }, { "code": null, "e": 3781, "s": 3755, "text": "Class and Object in Scala" }, { "code": null, "e": 3791, "s": 3781, "text": "Scala Map" }, { "code": null, "e": 3831, "s": 3791, "text": "Scala List filter() method with example" }, { "code": null, "e": 3884, "s": 3831, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 3896, "s": 3884, "text": "Scala Lists" }, { "code": null, "e": 3915, "s": 3896, "text": "Operators in Scala" }, { "code": null, "e": 3930, "s": 3915, "text": "Scala | Arrays" }, { "code": null, "e": 3949, "s": 3930, "text": "Scala Constructors" } ]
fileinput.filename() in Python
22 Apr, 2020 With the help of fileinput.filename() method, we can get the last used file name which we have used so far by using fileinput.filename() method. Syntax : fileinput.filename() Return : Return the last used file name. Example #1 :In this example we can see that by using fileinput.filename() method, we are able to get the last used file name by using this method. # import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files ='gfg.txt'): print(line) print(fileinput.filename()) Output : Example #2 : # import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files =('gfg.txt', 'gfg1.txt')): print(line) print(fileinput.filename()) Output : Python fileinput-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 173, "s": 28, "text": "With the help of fileinput.filename() method, we can get the last used file name which we have used so far by using fileinput.filename() method." }, { "code": null, "e": 203, "s": 173, "text": "Syntax : fileinput.filename()" }, { "code": null, "e": 244, "s": 203, "text": "Return : Return the last used file name." }, { "code": null, "e": 391, "s": 244, "text": "Example #1 :In this example we can see that by using fileinput.filename() method, we are able to get the last used file name by using this method." }, { "code": "# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files ='gfg.txt'): print(line) print(fileinput.filename())", "e": 550, "s": 391, "text": null }, { "code": null, "e": 559, "s": 550, "text": "Output :" }, { "code": null, "e": 572, "s": 559, "text": "Example #2 :" }, { "code": "# import fileinputimport fileinput # Using fileinput.input() methodfor line in fileinput.input(files =('gfg.txt', 'gfg1.txt')): print(line) print(fileinput.filename())", "e": 745, "s": 572, "text": null }, { "code": null, "e": 754, "s": 745, "text": "Output :" }, { "code": null, "e": 779, "s": 754, "text": "Python fileinput-library" }, { "code": null, "e": 786, "s": 779, "text": "Python" } ]
Setting up C++ Development Environment
25 May, 2022 C++ is a general-purpose programming language and widely used nowadays for competitive programming. It has imperative, object-oriented and generic programming features. C++ runs on lots of platform like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an environment to be set-up on our local computer to compile and run our C++ programs successfully. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using online IDE: IDE stands for integrated development environment. IDE is a software application that provides facilities to a computer programmer for developing software. There are many online IDEs available which you can use to compile and run your programs easily without setting up a local development environment.ide.geeksforgeeks.org is one such IDE provided by GeeksforGeeks. You can click on the Run on IDE button to run the program. CPP #include<iostream>using namespace std;main(){ cout << "Learning C++ at GeekforGeeks";} Setting up local environment For setting up your own personal development environment on your local machine you need to install two important softwares: Text Editor: Text Editors are type of programs used to edit or write texts. We will use text-editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file containing C++ program should be saved with ‘.CPP’ or ‘.C’ extension. Files ending with the extension ‘.CPP’ and ‘.C’ are called source code files and they are supposed to contain source code written in C++ programming language. These extension helps the compiler to identify that the file contains a C++ program. Before beginning programming with C++, one must have a text-editor installed to write programs. C++ Compiler: Once you have installed text-editor and typed and save your program in a file with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a computer program which converts high-level language into machine understandable low-level language. In other words, we can say that it converts the source code written in a programming language into another computer language which the computer understands. For compiling a C++ program we will need a C++ compiler which will convert the source code written in C++ into machine codes. Below are the details about setting up compiler on different platforms.Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: Text Editor: Text Editors are type of programs used to edit or write texts. We will use text-editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file containing C++ program should be saved with ‘.CPP’ or ‘.C’ extension. Files ending with the extension ‘.CPP’ and ‘.C’ are called source code files and they are supposed to contain source code written in C++ programming language. These extension helps the compiler to identify that the file contains a C++ program. Before beginning programming with C++, one must have a text-editor installed to write programs. C++ Compiler: Once you have installed text-editor and typed and save your program in a file with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a computer program which converts high-level language into machine understandable low-level language. In other words, we can say that it converts the source code written in a programming language into another computer language which the computer understands. For compiling a C++ program we will need a C++ compiler which will convert the source code written in C++ into machine codes. Below are the details about setting up compiler on different platforms.Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: You have to first run the below two commands from your Linux terminal window: sudo apt-get update sudo apt-get install gcc sudo apt-get install g++ This command will install the GCC compiler on your system. You may also run the below command: sudo apt-get install build-essential This command will install all the libraries which are required to compile and run a C++ program. After completing the above step, you should check whether the GCC compiler is installed in your system correctly or not. To do this you have to run the below-given command from Linux terminal: g++ --version If you have completed the above two steps without any errors, then your Linux environment is set up and ready to be used to compile C++ programs. In further steps, we will learn how to compile and run a C++ program on Linux using GCC compiler. Write your program in a text file and save it with any file name and.CPP extension. We have written a program to display “Hello World” and saved it in a file with the filename “helloworld.cpp” on desktop. Now you have to open the Linux terminal and move to the directory where you have saved your file. Then you have to run the below command to compile your file: g++ filename.cpp -o any-name filename.cpp is the name of your source code file. In our case, the name is “helloworld.cpp” and any-name can be any name of your choice. This name will be assigned to the executable file which is created by the compiler after compilation. In our case, we choose any-name to be “hello”. We will run the above command as: g++ helloworld.cpp -o hello After executing the above command, you will see a new file is created automatically in the same directory where you have saved the source file and the name of this file is the name you chose as any-name. Now to run your program you have to run the below command: ./hello This command will run your program in the terminal window. Windows Installation: There are lots of IDE available for windows operating system which you can use to work easily with C++ programming language. One of the popular IDE is Code::Blocks. To download Code::Blocks you may visit this link. Once you have downloaded the setup file of Code::Blocks from the given link open it and follow the instruction to install. After successfully installing Code::Blocks, go to File menu -> Select New and create an Empty file. Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension. After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run option. After successfully installing Code::Blocks, go to File menu -> Select New and create an Empty file. Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension. After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run option. Mac OS X Installation: If you are a Mac user,you have to download Xcode. To download Xcode you have to visit the apple website or you can search it on apple app store. You may follow the link developer.apple.com/technologies/tools/ to download Xcode. You will find all the necessary install instructions there. After successfully installing Xcode, open the Xcode application. To create a new project. Go to File menu -> select New -> select Project. This will create a new project for you. Now in the next window you have to choose a template for your project. To choose a C++ template choose Application option which is under the OS X section on the left side bar. Now choose command-line tools from available options and hit Next button. On the next window provide all the necessary details like ‘name of organisation’, ‘Product Name’ etc. But make sure to choose the language as C++ . After filling the details hit the next button to proceed to further steps. Choose the location where you want to save your project. After this choose the main.cpp file from the directory list on the left side-bar. Now after opening the main.cpp file, you will see a pre written c++ program or template is provided. You may change this program as per your requirement. To run your C++ program you have to go to Product menu and choose the Run option from the dropdown. After successfully installing Xcode, open the Xcode application. To create a new project. Go to File menu -> select New -> select Project. This will create a new project for you. Now in the next window you have to choose a template for your project. To choose a C++ template choose Application option which is under the OS X section on the left side bar. Now choose command-line tools from available options and hit Next button. On the next window provide all the necessary details like ‘name of organisation’, ‘Product Name’ etc. But make sure to choose the language as C++ . After filling the details hit the next button to proceed to further steps. Choose the location where you want to save your project. After this choose the main.cpp file from the directory list on the left side-bar. Now after opening the main.cpp file, you will see a pre written c++ program or template is provided. You may change this program as per your requirement. To run your C++ program you have to go to Product menu and choose the Run option from the dropdown. Another very easy to use and most popular IDE now a days, is VSC( Visual Studio Code), for both Windows and Mac OS. Window installation(VS Code ): Start with installing Visual Studio Code as per your windows. Open the downloaded file and click Run -> (Accept the agreement) Next -> Next -> Next -> (check all the options) -> Next ->Install->Finish. Now you’ll be able to see the Visual Studio Code icon on your desktop. o Download the MinGW from the link. o After Install, “Continue”. Check all the Packages (Right Click -> Mark for Installation). Now, Click on Installation (left corner) -> Apply Changes. (This may take time) o Open This PC -> C Drive -> MinGW -> Bin. (Copy this path) o Right Click on “This PC” -> Properties -> Advanced System Setting -> Environment variables -> (Select PATH in System variables) -> Edit -> New -> Paste the path here and OK. o Go to Visual Studio Code, and Install some useful extensions (from the right side bar, last icon(probably))- 1) C/C++ 2) Code Runner o Now, Go to Setting -> Settings -> Search for Terminal -> Go to the end of this page -> Check [ Code-runner: Run In Terminal ]Yayy! You are good to go now. Open any folder, create new files and Save them with extension “.cpp”. Mac OS Installation(VS Code): First of all, Install Visual Studio Code for Mac OS using this link. Then We’ll install the compiler MinGW. For this we first need to install Homebrew. o To install Homebrew, Open Terminal (cmd + space). Write Terminal and hit Enter. In cmd copy the given command arch -x86_64 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install)" < /dev/null 2> /dev/null This will download and install HomeBrew in your Mac system. This process may take time. 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. o Now We’ll install the MinGW compiler on Mac OS. Paste the given command in the terminal and press Enter. arch -x86_64 brew install MinGW-w64 This is also time taking process so be patient! o Go to Visual Studio Code, and Install some useful extensions (from the right side bar, last icon(probably))- 1) C/C++ 2) Code Runner o Now, Go to Setting -> Settings -> Search for Terminal -> Go to the end of this page -> Check [ Code-runner: Run In Terminal ] Yayy! You are good to go now. Now open any folder, create new files and Save them with extension “.cpp”. C++ Programming Language Tutorial | Setting up C++ Development Environment | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersC++ Programming Language Tutorial | Setting up C++ Development Environment | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=dsbj7XpHOcE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB This article is contributed by Harsh 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. darpsinghh surajsingh5092 anurag8546 C Basics CBSE - Class 11 CPP-Basics school-programming C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 May, 2022" }, { "code": null, "e": 988, "s": 53, "text": "C++ is a general-purpose programming language and widely used nowadays for competitive programming. It has imperative, object-oriented and generic programming features. C++ runs on lots of platform like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an environment to be set-up on our local computer to compile and run our C++ programs successfully. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using online IDE: IDE stands for integrated development environment. IDE is a software application that provides facilities to a computer programmer for developing software. There are many online IDEs available which you can use to compile and run your programs easily without setting up a local development environment.ide.geeksforgeeks.org is one such IDE provided by GeeksforGeeks. You can click on the Run on IDE button to run the program." }, { "code": null, "e": 992, "s": 988, "text": "CPP" }, { "code": "#include<iostream>using namespace std;main(){ cout << \"Learning C++ at GeekforGeeks\";}", "e": 1082, "s": 992, "text": null }, { "code": null, "e": 1111, "s": 1082, "text": "Setting up local environment" }, { "code": null, "e": 1236, "s": 1111, "text": "For setting up your own personal development environment on your local machine you need to install two important softwares: " }, { "code": null, "e": 2717, "s": 1236, "text": "Text Editor: Text Editors are type of programs used to edit or write texts. We will use text-editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file containing C++ program should be saved with ‘.CPP’ or ‘.C’ extension. Files ending with the extension ‘.CPP’ and ‘.C’ are called source code files and they are supposed to contain source code written in C++ programming language. These extension helps the compiler to identify that the file contains a C++ program. Before beginning programming with C++, one must have a text-editor installed to write programs. C++ Compiler: Once you have installed text-editor and typed and save your program in a file with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a computer program which converts high-level language into machine understandable low-level language. In other words, we can say that it converts the source code written in a programming language into another computer language which the computer understands. For compiling a C++ program we will need a C++ compiler which will convert the source code written in C++ into machine codes. Below are the details about setting up compiler on different platforms.Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: " }, { "code": null, "e": 3318, "s": 2717, "text": "Text Editor: Text Editors are type of programs used to edit or write texts. We will use text-editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file containing C++ program should be saved with ‘.CPP’ or ‘.C’ extension. Files ending with the extension ‘.CPP’ and ‘.C’ are called source code files and they are supposed to contain source code written in C++ programming language. These extension helps the compiler to identify that the file contains a C++ program. Before beginning programming with C++, one must have a text-editor installed to write programs. " }, { "code": null, "e": 4199, "s": 3318, "text": "C++ Compiler: Once you have installed text-editor and typed and save your program in a file with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a computer program which converts high-level language into machine understandable low-level language. In other words, we can say that it converts the source code written in a programming language into another computer language which the computer understands. For compiling a C++ program we will need a C++ compiler which will convert the source code written in C++ into machine codes. Below are the details about setting up compiler on different platforms.Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: " }, { "code": null, "e": 4444, "s": 4199, "text": "Linux Installation: We will install the GNU GCC compiler on Linux. To install and work with the GCC compiler on your Linux machine, proceed according to below steps: You have to first run the below two commands from your Linux terminal window: " }, { "code": null, "e": 4523, "s": 4444, "text": "You have to first run the below two commands from your Linux terminal window: " }, { "code": null, "e": 4593, "s": 4523, "text": "sudo apt-get update\nsudo apt-get install gcc\nsudo apt-get install g++" }, { "code": null, "e": 4689, "s": 4593, "text": "This command will install the GCC compiler on your system. You may also run the below command: " }, { "code": null, "e": 4726, "s": 4689, "text": "sudo apt-get install build-essential" }, { "code": null, "e": 4825, "s": 4726, "text": "This command will install all the libraries which are required to compile and run a C++ program. " }, { "code": null, "e": 5019, "s": 4825, "text": "After completing the above step, you should check whether the GCC compiler is installed in your system correctly or not. To do this you have to run the below-given command from Linux terminal: " }, { "code": null, "e": 5033, "s": 5019, "text": "g++ --version" }, { "code": null, "e": 5279, "s": 5033, "text": "If you have completed the above two steps without any errors, then your Linux environment is set up and ready to be used to compile C++ programs. In further steps, we will learn how to compile and run a C++ program on Linux using GCC compiler. " }, { "code": null, "e": 5486, "s": 5279, "text": "Write your program in a text file and save it with any file name and.CPP extension. We have written a program to display “Hello World” and saved it in a file with the filename “helloworld.cpp” on desktop. " }, { "code": null, "e": 5646, "s": 5486, "text": "Now you have to open the Linux terminal and move to the directory where you have saved your file. Then you have to run the below command to compile your file: " }, { "code": null, "e": 5675, "s": 5646, "text": "g++ filename.cpp -o any-name" }, { "code": null, "e": 5997, "s": 5675, "text": "filename.cpp is the name of your source code file. In our case, the name is “helloworld.cpp” and any-name can be any name of your choice. This name will be assigned to the executable file which is created by the compiler after compilation. In our case, we choose any-name to be “hello”. We will run the above command as: " }, { "code": null, "e": 6025, "s": 5997, "text": "g++ helloworld.cpp -o hello" }, { "code": null, "e": 6289, "s": 6025, "text": "After executing the above command, you will see a new file is created automatically in the same directory where you have saved the source file and the name of this file is the name you chose as any-name. Now to run your program you have to run the below command: " }, { "code": null, "e": 6297, "s": 6289, "text": "./hello" }, { "code": null, "e": 6358, "s": 6297, "text": "This command will run your program in the terminal window. " }, { "code": null, "e": 7009, "s": 6358, "text": "Windows Installation: There are lots of IDE available for windows operating system which you can use to work easily with C++ programming language. One of the popular IDE is Code::Blocks. To download Code::Blocks you may visit this link. Once you have downloaded the setup file of Code::Blocks from the given link open it and follow the instruction to install. After successfully installing Code::Blocks, go to File menu -> Select New and create an Empty file. Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension. After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run option. " }, { "code": null, "e": 7111, "s": 7009, "text": "After successfully installing Code::Blocks, go to File menu -> Select New and create an Empty file. " }, { "code": null, "e": 7202, "s": 7111, "text": "Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension. " }, { "code": null, "e": 7302, "s": 7202, "text": "After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run option. " }, { "code": null, "e": 8663, "s": 7302, "text": "Mac OS X Installation: If you are a Mac user,you have to download Xcode. To download Xcode you have to visit the apple website or you can search it on apple app store. You may follow the link developer.apple.com/technologies/tools/ to download Xcode. You will find all the necessary install instructions there. After successfully installing Xcode, open the Xcode application. To create a new project. Go to File menu -> select New -> select Project. This will create a new project for you. Now in the next window you have to choose a template for your project. To choose a C++ template choose Application option which is under the OS X section on the left side bar. Now choose command-line tools from available options and hit Next button. On the next window provide all the necessary details like ‘name of organisation’, ‘Product Name’ etc. But make sure to choose the language as C++ . After filling the details hit the next button to proceed to further steps. Choose the location where you want to save your project. After this choose the main.cpp file from the directory list on the left side-bar. Now after opening the main.cpp file, you will see a pre written c++ program or template is provided. You may change this program as per your requirement. To run your C++ program you have to go to Product menu and choose the Run option from the dropdown. " }, { "code": null, "e": 8730, "s": 8663, "text": "After successfully installing Xcode, open the Xcode application. " }, { "code": null, "e": 8846, "s": 8730, "text": "To create a new project. Go to File menu -> select New -> select Project. This will create a new project for you. " }, { "code": null, "e": 9098, "s": 8846, "text": "Now in the next window you have to choose a template for your project. To choose a C++ template choose Application option which is under the OS X section on the left side bar. Now choose command-line tools from available options and hit Next button. " }, { "code": null, "e": 9323, "s": 9098, "text": "On the next window provide all the necessary details like ‘name of organisation’, ‘Product Name’ etc. But make sure to choose the language as C++ . After filling the details hit the next button to proceed to further steps. " }, { "code": null, "e": 9463, "s": 9323, "text": "Choose the location where you want to save your project. After this choose the main.cpp file from the directory list on the left side-bar. " }, { "code": null, "e": 9718, "s": 9463, "text": "Now after opening the main.cpp file, you will see a pre written c++ program or template is provided. You may change this program as per your requirement. To run your C++ program you have to go to Product menu and choose the Run option from the dropdown. " }, { "code": null, "e": 9841, "s": 9718, "text": " Another very easy to use and most popular IDE now a days, is VSC( Visual Studio Code), for both Windows and Mac OS." }, { "code": null, "e": 11068, "s": 9841, "text": "Window installation(VS Code ): Start with installing Visual Studio Code as per your windows. Open the downloaded file and click Run -> (Accept the agreement) Next -> Next -> Next -> (check all the options) -> Next ->Install->Finish. Now you’ll be able to see the Visual Studio Code icon on your desktop. o Download the MinGW from the link. o After Install, “Continue”. Check all the Packages (Right Click -> Mark for Installation). Now, Click on Installation (left corner) -> Apply Changes. (This may take time) o Open This PC -> C Drive -> MinGW -> Bin. (Copy this path) o Right Click on “This PC” -> Properties -> Advanced System Setting -> Environment variables -> (Select PATH in System variables) -> Edit -> New -> Paste the path here and OK. o Go to Visual Studio Code, and Install some useful extensions (from the right side bar, last icon(probably))- 1) C/C++ 2) Code Runner o Now, Go to Setting -> Settings -> Search for Terminal -> Go to the end of this page -> Check [ Code-runner: Run In Terminal ]Yayy! You are good to go now. Open any folder, create new files and Save them with extension “.cpp”. " }, { "code": null, "e": 11371, "s": 11068, "text": "Mac OS Installation(VS Code): First of all, Install Visual Studio Code for Mac OS using this link. Then We’ll install the compiler MinGW. For this we first need to install Homebrew. o To install Homebrew, Open Terminal (cmd + space). Write Terminal and hit Enter. In cmd copy the given command " }, { "code": null, "e": 11497, "s": 11371, "text": "arch -x86_64 ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install)\" < /dev/null 2> /dev/null" }, { "code": null, "e": 11606, "s": 11497, "text": " This will download and install HomeBrew in your Mac system. This process may take time." }, { "code": null, "e": 11615, "s": 11606, "text": "Chapters" }, { "code": null, "e": 11642, "s": 11615, "text": "descriptions off, selected" }, { "code": null, "e": 11692, "s": 11642, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 11715, "s": 11692, "text": "captions off, selected" }, { "code": null, "e": 11723, "s": 11715, "text": "English" }, { "code": null, "e": 11747, "s": 11723, "text": "This is a modal window." }, { "code": null, "e": 11816, "s": 11747, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 11838, "s": 11816, "text": "End of dialog window." }, { "code": null, "e": 11960, "s": 11838, "text": " o Now We’ll install the MinGW compiler on Mac OS. Paste the given command in the terminal and press Enter." }, { "code": null, "e": 11998, "s": 11960, "text": "arch -x86_64 brew install MinGW-w64 " }, { "code": null, "e": 12080, "s": 11998, "text": " This is also time taking process so be patient! " }, { "code": null, "e": 12278, "s": 12080, "text": " o Go to Visual Studio Code, and Install some useful extensions (from the right side bar, last icon(probably))- 1) C/C++ 2) Code Runner" }, { "code": null, "e": 12392, "s": 12278, "text": " o Now, Go to Setting -> Settings -> Search for Terminal -> Go to the end of this page -> Check" }, { "code": null, "e": 12448, "s": 12392, "text": " [ Code-runner: Run In Terminal ]" }, { "code": null, "e": 12565, "s": 12448, "text": " Yayy! You are good to go now. Now open any folder, create new files and Save them with extension “.cpp”. " }, { "code": null, "e": 13531, "s": 12565, "text": "C++ Programming Language Tutorial | Setting up C++ Development Environment | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersC++ Programming Language Tutorial | Setting up C++ Development Environment | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=dsbj7XpHOcE\" 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": 13572, "s": 13531, "text": "?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB" }, { "code": null, "e": 13994, "s": 13572, "text": "This article is contributed by Harsh 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": 14005, "s": 13994, "text": "darpsinghh" }, { "code": null, "e": 14020, "s": 14005, "text": "surajsingh5092" }, { "code": null, "e": 14031, "s": 14020, "text": "anurag8546" }, { "code": null, "e": 14040, "s": 14031, "text": "C Basics" }, { "code": null, "e": 14056, "s": 14040, "text": "CBSE - Class 11" }, { "code": null, "e": 14067, "s": 14056, "text": "CPP-Basics" }, { "code": null, "e": 14086, "s": 14067, "text": "school-programming" }, { "code": null, "e": 14090, "s": 14086, "text": "C++" }, { "code": null, "e": 14109, "s": 14090, "text": "School Programming" }, { "code": null, "e": 14113, "s": 14109, "text": "CPP" } ]
Working with APIs in JavaScript
26 May, 2022 An API is simply a medium to fetch or send data between interfaces. Let’s say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Application Programming Interface. We will use a simple public API that requires no authentication and allows you to fetch some data by querying the API with GET requests. https://randomuser.me/ is a website that provides dummy data for random users that we can easily work with. We can get the response by making a request to https://randomuser.me/api/. The JSON response that we receive in the following format. Javascript { "results": [ { "gender": "female", "name": { "title": "Miss", "first": "Nina", "last": "Simmmons" }, "location": { "street": { "number": 970, "name": "Eason Rd" }, "city": "Fullerton", "state": "Wyoming", "country": "United States", "postcode": 57089, "coordinates": { "latitude": "83.1807", "longitude": "104.7170" }, "timezone": { "offset": "+8:00", "description": "Beijing, Perth, Singapore, Hong Kong" } }, "email": "[email protected]", "login": { "uuid": "bd0d135f-84df-4102-aa4f-5baaa41baf5c", "username": "yellowfrog722", "password": "dawg", "salt": "q28gdiyN", "md5": "291987daea22bb91775226574925b271", "sha1": "a0463a26ea5c2ff4f3ad498fd01c5994926e5021", "sha256":"6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a6fae4f5225f928" }, "dob": { "date": "1980-11-01T23:10:05.403Z", "age": 40 }, "registered": { "date": "2013-04-02T02:26:52.904Z", "age": 7 }, "phone": "(216)-693-7015", "cell": "(501)-534-9413", "id": { "name": "SSN", "value": "847-09-2973" }, "picture": { "large":"https://randomuser.me/api/portraits/women/60.jpg", "medium":"https://randomuser.me/api/portraits/med/women/60.jpg", "thumbnail":"https://randomuser.me/api/portraits/thumb/women/60.jpg" }, "nat": "US" } ], "info": { "seed": "82a8d8d4a996ba17", "results": 1, "page": 1, "version": "1.3" }} Next you need to have an HTML file for the frontend where you want to display the retrieved data. We can use either the “div” tag (block-level) or the “span” tag (inline-level), which will act as a place holder for the information. Using the “id” attribute, we can get the required “div/span” container where we want to place the information. HTML <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <link id="favicon" rel="icon" href="" sizes="16x16" /> <!-- font-awesome library to make the webpage more appealing --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <!-- Internal CSS styling --> <style> .content { text-align: center; padding: 30px; margin: 0px auto; } .details { margin-left: auto; margin-right: auto; } img { border-radius: 5px; box-shadow: black; } table, td { border-collapse: collapse; margin-left: auto; margin-right: auto; text-align: center; padding: 10px; border: 1px solid black; } </style></head> <body> <div class="content"> <div class="head"> <h1 id="head"></h1> </div> <div class="email"> <i class="fa fa-envelope" style= "font-size: 15px; color: blue;"></i> <a href="" id="email"> </a> </div> <div class="phone"> <i class="fa fa-phone" style= "font-size: 15px; color: blue;"></i> <a href="" id="phone"> </a> </div> <br /> <div id="user-img"></div> <br /> <div class="details"> <table> <tr> <td>Age</td> <td><span id="age"></span></td> </tr> <tr> <td>Gender</td> <td><span id="gender"></span></td> </tr> <tr> <td>Location</td> <td><span id="location"></span></td> </tr> <tr> <td>Country</td> <td><span id="country"></span></td> </tr> </table> </div> </div></body> </html> The script tag will contain the code that will make the API request and handle the response. This needs to be placed within the body tag or as a separate file. We use the async/await function that basically ensure that the data is displayed even after the page is loaded. You can use console.log(...) method to check if the user is retrieving correct piece of information. The output for the same can be seen by opening the console window in your web browser (Right Click -> Inspect -> Console or Ctrl+Shift+J in Chrome/Edge). Javascript <script> const api_url = "https://randomuser.me/api/"; async function getUser() { // Making an API call (request) // and getting the response back const response = await fetch(api_url); // Parsing it to JSON format const data = await response.json(); console.log(data.results); // Retrieving data from JSON const user = data.results[0]; let { title, first, last } = user.name; let { gender, email, phone } = user; let image = user.picture.large; let image_icon = user.picture.thumbnail; let age = user.dob.age; let { city, state, country } = user.location; let fullName = title + ". " + first + " " + last; document.title = fullName; // Accessing the div container and modify/add // elements to the containers document.getElementById("head").innerHTML = fullName; document.getElementById("email").href = "mailto:" + email; document.getElementById("email").innerHTML = email; document.getElementById("phone").href = "tel:" + phone; document.getElementById("phone").innerHTML = phone; // accessing the span container document.querySelector("#age").textContent = age; document.querySelector("#gender").textContent = gender; document.querySelector("#location").textContent = city + ", " + state; document.querySelector("#country").textContent = country; // Creating a new element and appending it // to previously created containers let img = document.createElement("img"); let img_div = document.getElementById("user-img"); img.src = image; img_div.append(img); const favicon = document.getElementById("favicon"); favicon.setAttribute("href", image_icon); } // Calling the function getUser();</script> Final code: It is the combination of the above code sections. HTML <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <!-- font-awesome library to make the webpage more appealing --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <!-- Internal CSS styling --> <style> .content { text-align: center; padding: 30px; margin: 0px auto; } .details { margin-left: auto; margin-right: auto; } img { border-radius: 5px; box-shadow: black; } table, td { border-collapse: collapse; margin-left: auto; margin-right: auto; text-align: center; padding: 10px; border: 1px solid black; } </style></head> <body> <div class="content"> <div class="head"> <h1 id="head"></h1> </div> <div class="email"> <i class="fa fa-envelope" style= "font-size: 15px; color: blue;"></i> <a href="" id="email"> </a> </div> <div class="phone"> <i class="fa fa-phone" style= "font-size: 15px; color: blue;"></i> <a href="" id="phone"> </a> </div> <br /> <div id="user-img"></div> <br /> <div class="details"> <table> <tr> <td>Age</td> <td><span id="age"></span></td> </tr> <tr> <td>Gender</td> <td><span id="gender"></span></td> </tr> <tr> <td>Location</td> <td><span id="location"></span></td> </tr> <tr> <td>Country</td> <td><span id="country"></span></td> </tr> </table> </div> </div></body><script> const api_url = "https://randomuser.me/api/"; async function getUser() { // Making an API call (request) // and getting the response back const response = await fetch(api_url); // Parsing it to JSON format const data = await response.json(); console.log(data.results); // Retrieving data from JSON const user = data.results[0]; let { title, first, last } = user.name; let { gender, email, phone } = user; let image = user.picture.large; let image_icon = user.picture.thumbnail; let age = user.dob.age; let { city, state, country } = user.location; let fullName = title + ". " + first + " " + last; document.title = fullName; // Accessing the div container and modify/add // elements to the containers document.getElementById("head").innerHTML = fullName; document.getElementById("email").href = "mailto:" + email; document.getElementById("email").innerHTML = email; document.getElementById("phone").href = "tel:" + phone; document.getElementById("phone").innerHTML = phone; // accessing the span container document.querySelector("#age").textContent = age; document.querySelector("#gender").textContent = gender; document.querySelector("#location").textContent = city + ", " + state; document.querySelector("#country").textContent = country; // Creating a new element and appending it // to previously created containers let img = document.createElement("img"); let img_div = document.getElementById("user-img"); img.src = image; img_div.append(img); const favicon = document.getElementById("favicon"); favicon.setAttribute("href", image_icon); } // Calling the function getUser();</script> </html> Output: Want to explore the APIs more and dive deeper into it, Refer Public APIs that has a vast collection of publicly available APIs to fuel your API exploration journey. To test an API for the type of response it gives Postman is an amazing application that will fulfill all your needs. You can use Postman API development article to get an insight into, how to use it. Another alternative is, Postman APIs which will help you do the same task on the browser itself. ruhelaa48 khushboogoyal499 CSS-Misc HTML-Misc JavaScript-Misc JSON CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 356, "s": 28, "text": "An API is simply a medium to fetch or send data between interfaces. Let’s say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Application Programming Interface." }, { "code": null, "e": 493, "s": 356, "text": "We will use a simple public API that requires no authentication and allows you to fetch some data by querying the API with GET requests." }, { "code": null, "e": 735, "s": 493, "text": "https://randomuser.me/ is a website that provides dummy data for random users that we can easily work with. We can get the response by making a request to https://randomuser.me/api/. The JSON response that we receive in the following format." }, { "code": null, "e": 746, "s": 735, "text": "Javascript" }, { "code": "{ \"results\": [ { \"gender\": \"female\", \"name\": { \"title\": \"Miss\", \"first\": \"Nina\", \"last\": \"Simmmons\" }, \"location\": { \"street\": { \"number\": 970, \"name\": \"Eason Rd\" }, \"city\": \"Fullerton\", \"state\": \"Wyoming\", \"country\": \"United States\", \"postcode\": 57089, \"coordinates\": { \"latitude\": \"83.1807\", \"longitude\": \"104.7170\" }, \"timezone\": { \"offset\": \"+8:00\", \"description\": \"Beijing, Perth, Singapore, Hong Kong\" } }, \"email\": \"[email protected]\", \"login\": { \"uuid\": \"bd0d135f-84df-4102-aa4f-5baaa41baf5c\", \"username\": \"yellowfrog722\", \"password\": \"dawg\", \"salt\": \"q28gdiyN\", \"md5\": \"291987daea22bb91775226574925b271\", \"sha1\": \"a0463a26ea5c2ff4f3ad498fd01c5994926e5021\", \"sha256\":\"6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a6fae4f5225f928\" }, \"dob\": { \"date\": \"1980-11-01T23:10:05.403Z\", \"age\": 40 }, \"registered\": { \"date\": \"2013-04-02T02:26:52.904Z\", \"age\": 7 }, \"phone\": \"(216)-693-7015\", \"cell\": \"(501)-534-9413\", \"id\": { \"name\": \"SSN\", \"value\": \"847-09-2973\" }, \"picture\": { \"large\":\"https://randomuser.me/api/portraits/women/60.jpg\", \"medium\":\"https://randomuser.me/api/portraits/med/women/60.jpg\", \"thumbnail\":\"https://randomuser.me/api/portraits/thumb/women/60.jpg\" }, \"nat\": \"US\" } ], \"info\": { \"seed\": \"82a8d8d4a996ba17\", \"results\": 1, \"page\": 1, \"version\": \"1.3\" }}", "e": 2852, "s": 746, "text": null }, { "code": null, "e": 2951, "s": 2852, "text": "Next you need to have an HTML file for the frontend where you want to display the retrieved data. " }, { "code": null, "e": 3196, "s": 2951, "text": "We can use either the “div” tag (block-level) or the “span” tag (inline-level), which will act as a place holder for the information. Using the “id” attribute, we can get the required “div/span” container where we want to place the information." }, { "code": null, "e": 3201, "s": 3196, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <link id=\"favicon\" rel=\"icon\" href=\"\" sizes=\"16x16\" /> <!-- font-awesome library to make the webpage more appealing --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <!-- Internal CSS styling --> <style> .content { text-align: center; padding: 30px; margin: 0px auto; } .details { margin-left: auto; margin-right: auto; } img { border-radius: 5px; box-shadow: black; } table, td { border-collapse: collapse; margin-left: auto; margin-right: auto; text-align: center; padding: 10px; border: 1px solid black; } </style></head> <body> <div class=\"content\"> <div class=\"head\"> <h1 id=\"head\"></h1> </div> <div class=\"email\"> <i class=\"fa fa-envelope\" style= \"font-size: 15px; color: blue;\"></i> <a href=\"\" id=\"email\"> </a> </div> <div class=\"phone\"> <i class=\"fa fa-phone\" style= \"font-size: 15px; color: blue;\"></i> <a href=\"\" id=\"phone\"> </a> </div> <br /> <div id=\"user-img\"></div> <br /> <div class=\"details\"> <table> <tr> <td>Age</td> <td><span id=\"age\"></span></td> </tr> <tr> <td>Gender</td> <td><span id=\"gender\"></span></td> </tr> <tr> <td>Location</td> <td><span id=\"location\"></span></td> </tr> <tr> <td>Country</td> <td><span id=\"country\"></span></td> </tr> </table> </div> </div></body> </html>", "e": 4935, "s": 3201, "text": null }, { "code": null, "e": 5095, "s": 4935, "text": "The script tag will contain the code that will make the API request and handle the response. This needs to be placed within the body tag or as a separate file." }, { "code": null, "e": 5207, "s": 5095, "text": "We use the async/await function that basically ensure that the data is displayed even after the page is loaded." }, { "code": null, "e": 5462, "s": 5207, "text": "You can use console.log(...) method to check if the user is retrieving correct piece of information. The output for the same can be seen by opening the console window in your web browser (Right Click -> Inspect -> Console or Ctrl+Shift+J in Chrome/Edge)." }, { "code": null, "e": 5473, "s": 5462, "text": "Javascript" }, { "code": "<script> const api_url = \"https://randomuser.me/api/\"; async function getUser() { // Making an API call (request) // and getting the response back const response = await fetch(api_url); // Parsing it to JSON format const data = await response.json(); console.log(data.results); // Retrieving data from JSON const user = data.results[0]; let { title, first, last } = user.name; let { gender, email, phone } = user; let image = user.picture.large; let image_icon = user.picture.thumbnail; let age = user.dob.age; let { city, state, country } = user.location; let fullName = title + \". \" + first + \" \" + last; document.title = fullName; // Accessing the div container and modify/add // elements to the containers document.getElementById(\"head\").innerHTML = fullName; document.getElementById(\"email\").href = \"mailto:\" + email; document.getElementById(\"email\").innerHTML = email; document.getElementById(\"phone\").href = \"tel:\" + phone; document.getElementById(\"phone\").innerHTML = phone; // accessing the span container document.querySelector(\"#age\").textContent = age; document.querySelector(\"#gender\").textContent = gender; document.querySelector(\"#location\").textContent = city + \", \" + state; document.querySelector(\"#country\").textContent = country; // Creating a new element and appending it // to previously created containers let img = document.createElement(\"img\"); let img_div = document.getElementById(\"user-img\"); img.src = image; img_div.append(img); const favicon = document.getElementById(\"favicon\"); favicon.setAttribute(\"href\", image_icon); } // Calling the function getUser();</script>", "e": 7206, "s": 5473, "text": null }, { "code": null, "e": 7268, "s": 7206, "text": "Final code: It is the combination of the above code sections." }, { "code": null, "e": 7273, "s": 7268, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <!-- font-awesome library to make the webpage more appealing --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <!-- Internal CSS styling --> <style> .content { text-align: center; padding: 30px; margin: 0px auto; } .details { margin-left: auto; margin-right: auto; } img { border-radius: 5px; box-shadow: black; } table, td { border-collapse: collapse; margin-left: auto; margin-right: auto; text-align: center; padding: 10px; border: 1px solid black; } </style></head> <body> <div class=\"content\"> <div class=\"head\"> <h1 id=\"head\"></h1> </div> <div class=\"email\"> <i class=\"fa fa-envelope\" style= \"font-size: 15px; color: blue;\"></i> <a href=\"\" id=\"email\"> </a> </div> <div class=\"phone\"> <i class=\"fa fa-phone\" style= \"font-size: 15px; color: blue;\"></i> <a href=\"\" id=\"phone\"> </a> </div> <br /> <div id=\"user-img\"></div> <br /> <div class=\"details\"> <table> <tr> <td>Age</td> <td><span id=\"age\"></span></td> </tr> <tr> <td>Gender</td> <td><span id=\"gender\"></span></td> </tr> <tr> <td>Location</td> <td><span id=\"location\"></span></td> </tr> <tr> <td>Country</td> <td><span id=\"country\"></span></td> </tr> </table> </div> </div></body><script> const api_url = \"https://randomuser.me/api/\"; async function getUser() { // Making an API call (request) // and getting the response back const response = await fetch(api_url); // Parsing it to JSON format const data = await response.json(); console.log(data.results); // Retrieving data from JSON const user = data.results[0]; let { title, first, last } = user.name; let { gender, email, phone } = user; let image = user.picture.large; let image_icon = user.picture.thumbnail; let age = user.dob.age; let { city, state, country } = user.location; let fullName = title + \". \" + first + \" \" + last; document.title = fullName; // Accessing the div container and modify/add // elements to the containers document.getElementById(\"head\").innerHTML = fullName; document.getElementById(\"email\").href = \"mailto:\" + email; document.getElementById(\"email\").innerHTML = email; document.getElementById(\"phone\").href = \"tel:\" + phone; document.getElementById(\"phone\").innerHTML = phone; // accessing the span container document.querySelector(\"#age\").textContent = age; document.querySelector(\"#gender\").textContent = gender; document.querySelector(\"#location\").textContent = city + \", \" + state; document.querySelector(\"#country\").textContent = country; // Creating a new element and appending it // to previously created containers let img = document.createElement(\"img\"); let img_div = document.getElementById(\"user-img\"); img.src = image; img_div.append(img); const favicon = document.getElementById(\"favicon\"); favicon.setAttribute(\"href\", image_icon); } // Calling the function getUser();</script> </html>", "e": 10676, "s": 7273, "text": null }, { "code": null, "e": 10685, "s": 10676, "text": "Output: " }, { "code": null, "e": 10850, "s": 10685, "text": "Want to explore the APIs more and dive deeper into it, Refer Public APIs that has a vast collection of publicly available APIs to fuel your API exploration journey." }, { "code": null, "e": 11147, "s": 10850, "text": "To test an API for the type of response it gives Postman is an amazing application that will fulfill all your needs. You can use Postman API development article to get an insight into, how to use it. Another alternative is, Postman APIs which will help you do the same task on the browser itself." }, { "code": null, "e": 11159, "s": 11149, "text": "ruhelaa48" }, { "code": null, "e": 11176, "s": 11159, "text": "khushboogoyal499" }, { "code": null, "e": 11185, "s": 11176, "text": "CSS-Misc" }, { "code": null, "e": 11195, "s": 11185, "text": "HTML-Misc" }, { "code": null, "e": 11211, "s": 11195, "text": "JavaScript-Misc" }, { "code": null, "e": 11216, "s": 11211, "text": "JSON" }, { "code": null, "e": 11220, "s": 11216, "text": "CSS" }, { "code": null, "e": 11225, "s": 11220, "text": "HTML" }, { "code": null, "e": 11236, "s": 11225, "text": "JavaScript" }, { "code": null, "e": 11253, "s": 11236, "text": "Web Technologies" }, { "code": null, "e": 11280, "s": 11253, "text": "Web technologies Questions" }, { "code": null, "e": 11285, "s": 11280, "text": "HTML" }, { "code": null, "e": 11383, "s": 11285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11431, "s": 11383, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 11493, "s": 11431, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 11543, "s": 11493, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 11601, "s": 11543, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 11651, "s": 11601, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 11699, "s": 11651, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 11761, "s": 11699, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 11811, "s": 11761, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 11835, "s": 11811, "text": "REST API (Introduction)" } ]
Shift 2D Grid in C++
Suppose we have one 2D grid of size m x n. We have another variable k. We have to shift the grid k times. The shift operation will be as follows Element at grid G[i, j] moves to G[i, j + 1] Element at grid G[i, j] moves to G[i, j + 1] Element at grid G[i, n – 1] moves to G[i + 1, 0] Element at grid G[i, n – 1] moves to G[i + 1, 0] Element at grid G[m - 1, n – 1] moves to G[0, 0] Element at grid G[m - 1, n – 1] moves to G[0, 0] So if the grid is like − The output will be − To solve this, we will follow these steps − The shift operation will take the matrix as input The shift operation will take the matrix as input n = number of rows, m := number of columns, x := bottom right element n = number of rows, m := number of columns, x := bottom right element for i := n – 1, down to 0for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1] for i := n – 1, down to 0 for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1] for j := m – 1 down to 0 if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1] if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1] else if j > 0, then G[i, j] := G[i, j – 1] else if j > 0, then G[i, j] := G[i, j – 1] G[0, 0] := x G[0, 0] := x Call the shift operation by the following rule − Call the shift operation by the following rule − while k is not 0shift the grid Gdecrease k by 1 while k is not 0 shift the grid G shift the grid G decrease k by 1 decrease k by 1 return grid G return grid G Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<int> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] <<", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: void shift(vector<vector<int>>& grid){ int n = grid.size(); int m = grid[0].size(); int x = grid[n-1][m-1]; for(int i = n-1; i>=0; i--){ for(int j = m-1;j>=0;j--){ if(j == 0 && i>0){ grid[i][j] = grid[i-1][m-1]; } else if(j>0){ grid[i][j] = grid[i][j-1]; } } } grid[0][0] = x; } vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) { while(k--){ shift(g); } return g; } }; main(){ Solution ob; vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}}; print_vector(ob.shiftGrid(mat, 1)); } {{1,2,3},{4,5,6},{7,8,9}} 1 [[9, 1, 2, ],[3, 4, 5, ],[6, 7, 8, ],]
[ { "code": null, "e": 1207, "s": 1062, "text": "Suppose we have one 2D grid of size m x n. We have another variable k. We have to shift the\ngrid k times. The shift operation will be as follows" }, { "code": null, "e": 1252, "s": 1207, "text": "Element at grid G[i, j] moves to G[i, j + 1]" }, { "code": null, "e": 1297, "s": 1252, "text": "Element at grid G[i, j] moves to G[i, j + 1]" }, { "code": null, "e": 1346, "s": 1297, "text": "Element at grid G[i, n – 1] moves to G[i + 1, 0]" }, { "code": null, "e": 1395, "s": 1346, "text": "Element at grid G[i, n – 1] moves to G[i + 1, 0]" }, { "code": null, "e": 1444, "s": 1395, "text": "Element at grid G[m - 1, n – 1] moves to G[0, 0]" }, { "code": null, "e": 1493, "s": 1444, "text": "Element at grid G[m - 1, n – 1] moves to G[0, 0]" }, { "code": null, "e": 1518, "s": 1493, "text": "So if the grid is like −" }, { "code": null, "e": 1539, "s": 1518, "text": "The output will be −" }, { "code": null, "e": 1583, "s": 1539, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1633, "s": 1583, "text": "The shift operation will take the matrix as input" }, { "code": null, "e": 1683, "s": 1633, "text": "The shift operation will take the matrix as input" }, { "code": null, "e": 1753, "s": 1683, "text": "n = number of rows, m := number of columns, x := bottom right element" }, { "code": null, "e": 1823, "s": 1753, "text": "n = number of rows, m := number of columns, x := bottom right element" }, { "code": null, "e": 1966, "s": 1823, "text": "for i := n – 1, down to 0for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1]" }, { "code": null, "e": 1992, "s": 1966, "text": "for i := n – 1, down to 0" }, { "code": null, "e": 2110, "s": 1992, "text": "for j := m – 1 down to 0if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]else if j > 0, then G[i, j] := G[i, j – 1]" }, { "code": null, "e": 2135, "s": 2110, "text": "for j := m – 1 down to 0" }, { "code": null, "e": 2187, "s": 2135, "text": "if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]" }, { "code": null, "e": 2239, "s": 2187, "text": "if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]" }, { "code": null, "e": 2282, "s": 2239, "text": "else if j > 0, then G[i, j] := G[i, j – 1]" }, { "code": null, "e": 2325, "s": 2282, "text": "else if j > 0, then G[i, j] := G[i, j – 1]" }, { "code": null, "e": 2338, "s": 2325, "text": "G[0, 0] := x" }, { "code": null, "e": 2351, "s": 2338, "text": "G[0, 0] := x" }, { "code": null, "e": 2400, "s": 2351, "text": "Call the shift operation by the following rule −" }, { "code": null, "e": 2449, "s": 2400, "text": "Call the shift operation by the following rule −" }, { "code": null, "e": 2497, "s": 2449, "text": "while k is not 0shift the grid Gdecrease k by 1" }, { "code": null, "e": 2514, "s": 2497, "text": "while k is not 0" }, { "code": null, "e": 2531, "s": 2514, "text": "shift the grid G" }, { "code": null, "e": 2548, "s": 2531, "text": "shift the grid G" }, { "code": null, "e": 2564, "s": 2548, "text": "decrease k by 1" }, { "code": null, "e": 2580, "s": 2564, "text": "decrease k by 1" }, { "code": null, "e": 2594, "s": 2580, "text": "return grid G" }, { "code": null, "e": 2608, "s": 2594, "text": "return grid G" }, { "code": null, "e": 2680, "s": 2608, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2691, "s": 2680, "text": " Live Demo" }, { "code": null, "e": 3682, "s": 2691, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<vector<int> > v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] <<\", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n void shift(vector<vector<int>>& grid){\n int n = grid.size();\n int m = grid[0].size();\n int x = grid[n-1][m-1];\n for(int i = n-1; i>=0; i--){\n for(int j = m-1;j>=0;j--){\n if(j == 0 && i>0){\n grid[i][j] = grid[i-1][m-1];\n }\n else if(j>0){\n grid[i][j] = grid[i][j-1];\n }\n }\n }\n grid[0][0] = x;\n }\n vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) {\n while(k--){\n shift(g);\n }\n return g;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};\n print_vector(ob.shiftGrid(mat, 1));\n}" }, { "code": null, "e": 3710, "s": 3682, "text": "{{1,2,3},{4,5,6},{7,8,9}}\n1" }, { "code": null, "e": 3749, "s": 3710, "text": "[[9, 1, 2, ],[3, 4, 5, ],[6, 7, 8, ],]" } ]
\underbrace - Tex Command
\underbrace - Used to put a (stretchy) under-brace under the argument. { \underbrace #1} \underbrace command is used to put a (stretchy) under-brace under the argument. \underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}} x+⋯+x⏟n times(note here) \underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}} x+⋯+x⏟n times(note here) \underbrace{x + \cdots + x}_{n\rm\ times}^{\text{(note here)}} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8057, "s": 7986, "text": "\\underbrace - Used to put a (stretchy) under-brace under the argument." }, { "code": null, "e": 8075, "s": 8057, "text": "{ \\underbrace #1}" }, { "code": null, "e": 8155, "s": 8075, "text": "\\underbrace command is used to put a (stretchy) under-brace under the argument." }, { "code": null, "e": 8248, "s": 8155, "text": "\n\\underbrace{x + \\cdots + x}_{n\\rm\\ times}^{\\text{(note here)}}\n\nx+⋯+x⏟n times(note here)\n\n\n" }, { "code": null, "e": 8339, "s": 8248, "text": "\\underbrace{x + \\cdots + x}_{n\\rm\\ times}^{\\text{(note here)}}\n\nx+⋯+x⏟n times(note here)\n\n" }, { "code": null, "e": 8402, "s": 8339, "text": "\\underbrace{x + \\cdots + x}_{n\\rm\\ times}^{\\text{(note here)}}" }, { "code": null, "e": 8434, "s": 8402, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8447, "s": 8434, "text": " Ashraf Said" }, { "code": null, "e": 8480, "s": 8447, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8493, "s": 8480, "text": " Ashraf Said" }, { "code": null, "e": 8525, "s": 8493, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8561, "s": 8525, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8596, "s": 8561, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8613, "s": 8596, "text": " Mohammad Nauman" }, { "code": null, "e": 8646, "s": 8613, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8660, "s": 8646, "text": " Daniel Stern" }, { "code": null, "e": 8692, "s": 8660, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8707, "s": 8692, "text": " Nishant Kumar" }, { "code": null, "e": 8714, "s": 8707, "text": " Print" }, { "code": null, "e": 8725, "s": 8714, "text": " Add Notes" } ]
How to Resize Images Using Python | by Nicholas Ballard | Towards Data Science
It would be a safe bet saying every “person of the computer” has needed to resize an image at one time or another. MacOS’ Preview can do it; so can Windows PowerToys. If you understand Photoshop or Gimp, then you and I... We are not the same. Command line utilities? Okay, now that is something I can wrap my head around. Lucky for us, image manipulation, and command line tooling, are two specialties of Python. This article aims to show you three things: Basics of what an image is.Python libraries for manipulating images.Code you can take and use in your own projects. Basics of what an image is. Python libraries for manipulating images. Code you can take and use in your own projects. The command line program we are going to build can resize one or multiple image files at once. Let’s jump in! For this example, we are going to create our own image rather than find a real one to manipulate. Why? Because I have to over-complicate things, that’s why! Actually, creating our own is a good way to illustrate what an image actually is. This resizing program will work just as well on anything from Instagram. So, what is an image? In Python data terms, an image is a list of lists of tuples of integers. image = list[list[tuple[*int, float]]] A NumPyesque definition would be a two-dimensional array of shape (h, w, 4), with h the number of pixels high (up and down), and w the number of pixels across (left to right). In other words, an image is a list (whole image) of lists (rows) of pixels (cells). Each pixel is a sequence of 3 integers and 1 optional float: red channel, green channel, blue channel, alpha (float that is optional). The red, green, blue channels — RGB — have a value from 0 to 255. From here on out we’ll talk about color images without alpha channel to keep it simple. Alpha is the transparency of the pixel. Images can also have only one channel with a value from 0 to 255. This is what greyscale — aka black and white — images are. But this is the real world... we work with color images! import matplotlib as plt​pixel: tuple = (200, 100, 150)plt.imshow([[list(pixel)]]) Hot. Vanilla Python is fully capable of creating an image. To display it, I will use the matplotlib library, which you can install with: pip install matplotlib Creating a Pixel: Creating an image: That is the image rendered. Behind the scenes, this is what the data looks like (for a 90x90): [[[234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [234, 162, 33], ... Now that we have an image, let’s get resizing it! Psych! We will not be writing an algorithm for resizing images in Python. Why? TLDR: It’s too much work. There is so much that goes into image processing algorithms. Some people dedicate their lives to it. Resampling–using one pixel in a scaled down image to stand in for the many around it in the higher resolution–is a huge topic by itself. If you want to see for yourself, check out Image.py in Pillow's source code when you install it at path/to/site-packages/PIL. Then there are optimizations like antialiasing and gap-reduction... It’s endless. We’re going to stand on the shoulders of giants here, meaning trust the brilliant work of those in the computer vision field, and shamelessly invoke one-liners to solve our problems. If you are interested in learning more about what is going on behind the curtain when processing images, I encourage you to check out the topic of “machine vision” more! It is definitely a booming field, and there’s more niches to explore than one person has time. Get good enough, and there’s a legion of companies willing to pay top dollar for your computer vision expertise. Self-driving, IoT, surveillance, you name it; all rely fundamentally on processing pictures (usually in Python or C++). A great place to start is checking out scikit-image. OpenCV is the end-all, be-all for image processing. Written in C++ and ported to Python, OpenCV is what runs in the trunk of your homemade self-driving car for lane detection. The options for the interpolation argument are one of the flags provided in the cv2 package: INTER_NEAREST – a nearest-neighbor interpolation INTER_LINEAR – a bilinear interpolation (used by default) INTER_AREA – resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. INTER_CUBIC – a bicubic interpolation over 4×4 pixel neighborhood INTER_LANCZOS4 – a Lanczos interpolation over 8×8 pixel neighborhood And this returns: It did what we expected. The image went from 900 pixels high, and 900 pixels across, to 450 X 450 (and still three color channels). The screenshot above doesn’t look so good because of matplotlib colorizations in Jupyter Lab. The pillow library has a resizing method on the Image class. The arguments it takes are: size: (width, height)resample: Defaults to BICUBIC. A flag for the resampling algorithm.box: Defaults to None. A 4-tuple defining a rectangle of the image to work on within parameters (0, 0, width, height).reducing_gap: Defaults to None. A resampling optimization algorithm to make the output look better. Here it is for our purposes in a function: The function using Pillow is very much the same as OpenCV. The only difference is the PIL.Image.Image class has an attribute size to access the (width, height) of the image. The result: Notice how the show method opens the operating system's default program for viewing the image's file type. Now we have a function for resizing images, it’s time to bring it full circle with an interface for running the resize. Resizing one image is fine. But if we are going through all this trouble, we want the ability to process images in bulk, too. The interface we are going to build will be the simplest one possible: a command line utility. The Pallets Project is the community of geniuses behind Flask, the Jinja template engine, and relevant to us right now: Click. pip install click Click is a library for making command line programs. It is way better than using plain argparse or whipping up some if-then logic in the if __name__ == '__main__': statement. So, we're going to use Click to decorate our image resizer. Here is the full script for resizing images from the command line! The command line program runs from the entrypoint function main. Arguments are passed to main by click.option decorators: pattern takes a Python / RE2 style string to locate the image or images relative to the directory where the script is running. --pattern="../catpics/*.png" will go up one level and find the catpics folder, and return any files in that folder with the .png image extension. scale takes a number, float or integer, and passes this to the resize function. This script is simple, and that means no data validation. Bonus if you add to the code, checking scale is a number between let's say, 5 and 99 (reasonable down-scaling parameters). As it stands right now, you can pass -s "chicken nuggets" and an Exception won't be thrown until Pillow stops the program. quiet is an option argument if you do not want text printing to standard out while the program is running. Run the program from the command line: python resize.py -s 35 -p "./*jpg" Result: $ py resize.py -p "checkers.jpg" -s 90resized image saved to checkers_90_810x810.jpg. Checking the folder: $ ls -lh checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg Nice! So the program downsized the image, gave it a descriptive label, and we can see the file size went from ~362KB to ~231KB! Just to see the program working on multiple files at once, we’ll run it again: $ py resize.py --pattern="checkers*" --scale=20resized image saved to checkers_20_180x180.jpg.resized image saved to checkers_90_810x810_20_162x162.jpg. And the file system: $ ll -h checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_20_180x180.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_90_810x810_20_162x162.jpg Okay, running the program recursively is only for crazy people, but it shows you can run on any number of images matching the pattern all at once. Go, automation! Bonus Click is an amazing tool. It can wrap a function and run in a module “the normal way” from an if __name__ == '__main__': statement. (And actually, it doesn’t even need that; you can just define and decorate the function you want to run.) But where it really shines is installing the script as a package. That is done with the setuptools library that comes with Python. Here is my setup.py. Build the executables / wrap the package with the command: pip install -e . Now you can invoke the script without using the python command. Also–as a bonus bonus–if you add the new executable to a folder in your PATH, you can call this program from anywhere on your computer like resize -p *jpg -s 75! This tutorial bounced around quite a bit: first going over some of the third party Python libraries for image manipulation. Then building an image from scratch using Python to understand a little more about what an image actually is. Then, choosing one of the options and building a script to downscale images while keeping their proportions. And, finally–inhales–putting that all in a command line utility accepting configurable options with click. A few more sentences and I’m done, I promise. I just wanted to say: there is a reason as to why I covered all these topics in one go with you. And that reason is not because I have ADHD. It’s because programming ideas need to close the loop from idea to execution. A one-off concept on how to do something in Python is fine... but at the end of the day, a programming language is a tool. It needs to help us get stuff done to have any value. When you start to feel tutorials are overwhelming you with “yet another thing you have to learn”–it means it’s time to take a break from reading, and start coding on some small project. Something you can complete in one sitting, and feel you have made progress. Remember, code can take hours or days to write. Yet it takes only milliseconds to run. The programs you make don’t have to be big. Any single thing you build that can save you time or let you produce more output, can potentially serve you for the rest of your life!
[ { "code": null, "e": 339, "s": 172, "text": "It would be a safe bet saying every “person of the computer” has needed to resize an image at one time or another. MacOS’ Preview can do it; so can Windows PowerToys." }, { "code": null, "e": 494, "s": 339, "text": "If you understand Photoshop or Gimp, then you and I... We are not the same. Command line utilities? Okay, now that is something I can wrap my head around." }, { "code": null, "e": 585, "s": 494, "text": "Lucky for us, image manipulation, and command line tooling, are two specialties of Python." }, { "code": null, "e": 629, "s": 585, "text": "This article aims to show you three things:" }, { "code": null, "e": 745, "s": 629, "text": "Basics of what an image is.Python libraries for manipulating images.Code you can take and use in your own projects." }, { "code": null, "e": 773, "s": 745, "text": "Basics of what an image is." }, { "code": null, "e": 815, "s": 773, "text": "Python libraries for manipulating images." }, { "code": null, "e": 863, "s": 815, "text": "Code you can take and use in your own projects." }, { "code": null, "e": 958, "s": 863, "text": "The command line program we are going to build can resize one or multiple image files at once." }, { "code": null, "e": 973, "s": 958, "text": "Let’s jump in!" }, { "code": null, "e": 1071, "s": 973, "text": "For this example, we are going to create our own image rather than find a real one to manipulate." }, { "code": null, "e": 1130, "s": 1071, "text": "Why? Because I have to over-complicate things, that’s why!" }, { "code": null, "e": 1285, "s": 1130, "text": "Actually, creating our own is a good way to illustrate what an image actually is. This resizing program will work just as well on anything from Instagram." }, { "code": null, "e": 1380, "s": 1285, "text": "So, what is an image? In Python data terms, an image is a list of lists of tuples of integers." }, { "code": null, "e": 1419, "s": 1380, "text": "image = list[list[tuple[*int, float]]]" }, { "code": null, "e": 1595, "s": 1419, "text": "A NumPyesque definition would be a two-dimensional array of shape (h, w, 4), with h the number of pixels high (up and down), and w the number of pixels across (left to right)." }, { "code": null, "e": 1880, "s": 1595, "text": "In other words, an image is a list (whole image) of lists (rows) of pixels (cells). Each pixel is a sequence of 3 integers and 1 optional float: red channel, green channel, blue channel, alpha (float that is optional). The red, green, blue channels — RGB — have a value from 0 to 255." }, { "code": null, "e": 2190, "s": 1880, "text": "From here on out we’ll talk about color images without alpha channel to keep it simple. Alpha is the transparency of the pixel. Images can also have only one channel with a value from 0 to 255. This is what greyscale — aka black and white — images are. But this is the real world... we work with color images!" }, { "code": null, "e": 2273, "s": 2190, "text": "import matplotlib as plt​pixel: tuple = (200, 100, 150)plt.imshow([[list(pixel)]])" }, { "code": null, "e": 2278, "s": 2273, "text": "Hot." }, { "code": null, "e": 2410, "s": 2278, "text": "Vanilla Python is fully capable of creating an image. To display it, I will use the matplotlib library, which you can install with:" }, { "code": null, "e": 2433, "s": 2410, "text": "pip install matplotlib" }, { "code": null, "e": 2451, "s": 2433, "text": "Creating a Pixel:" }, { "code": null, "e": 2470, "s": 2451, "text": "Creating an image:" }, { "code": null, "e": 2565, "s": 2470, "text": "That is the image rendered. Behind the scenes, this is what the data looks like (for a 90x90):" }, { "code": null, "e": 2898, "s": 2565, "text": "[[[234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [234, 162, 33], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [234, 162, 33], ..." }, { "code": null, "e": 2948, "s": 2898, "text": "Now that we have an image, let’s get resizing it!" }, { "code": null, "e": 3022, "s": 2948, "text": "Psych! We will not be writing an algorithm for resizing images in Python." }, { "code": null, "e": 3027, "s": 3022, "text": "Why?" }, { "code": null, "e": 3053, "s": 3027, "text": "TLDR: It’s too much work." }, { "code": null, "e": 3417, "s": 3053, "text": "There is so much that goes into image processing algorithms. Some people dedicate their lives to it. Resampling–using one pixel in a scaled down image to stand in for the many around it in the higher resolution–is a huge topic by itself. If you want to see for yourself, check out Image.py in Pillow's source code when you install it at path/to/site-packages/PIL." }, { "code": null, "e": 3682, "s": 3417, "text": "Then there are optimizations like antialiasing and gap-reduction... It’s endless. We’re going to stand on the shoulders of giants here, meaning trust the brilliant work of those in the computer vision field, and shamelessly invoke one-liners to solve our problems." }, { "code": null, "e": 3947, "s": 3682, "text": "If you are interested in learning more about what is going on behind the curtain when processing images, I encourage you to check out the topic of “machine vision” more! It is definitely a booming field, and there’s more niches to explore than one person has time." }, { "code": null, "e": 4180, "s": 3947, "text": "Get good enough, and there’s a legion of companies willing to pay top dollar for your computer vision expertise. Self-driving, IoT, surveillance, you name it; all rely fundamentally on processing pictures (usually in Python or C++)." }, { "code": null, "e": 4233, "s": 4180, "text": "A great place to start is checking out scikit-image." }, { "code": null, "e": 4409, "s": 4233, "text": "OpenCV is the end-all, be-all for image processing. Written in C++ and ported to Python, OpenCV is what runs in the trunk of your homemade self-driving car for lane detection." }, { "code": null, "e": 4502, "s": 4409, "text": "The options for the interpolation argument are one of the flags provided in the cv2 package:" }, { "code": null, "e": 4952, "s": 4502, "text": "INTER_NEAREST – a nearest-neighbor interpolation INTER_LINEAR – a bilinear interpolation (used by default) INTER_AREA – resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. INTER_CUBIC – a bicubic interpolation over 4×4 pixel neighborhood INTER_LANCZOS4 – a Lanczos interpolation over 8×8 pixel neighborhood" }, { "code": null, "e": 4970, "s": 4952, "text": "And this returns:" }, { "code": null, "e": 5196, "s": 4970, "text": "It did what we expected. The image went from 900 pixels high, and 900 pixels across, to 450 X 450 (and still three color channels). The screenshot above doesn’t look so good because of matplotlib colorizations in Jupyter Lab." }, { "code": null, "e": 5285, "s": 5196, "text": "The pillow library has a resizing method on the Image class. The arguments it takes are:" }, { "code": null, "e": 5591, "s": 5285, "text": "size: (width, height)resample: Defaults to BICUBIC. A flag for the resampling algorithm.box: Defaults to None. A 4-tuple defining a rectangle of the image to work on within parameters (0, 0, width, height).reducing_gap: Defaults to None. A resampling optimization algorithm to make the output look better." }, { "code": null, "e": 5634, "s": 5591, "text": "Here it is for our purposes in a function:" }, { "code": null, "e": 5808, "s": 5634, "text": "The function using Pillow is very much the same as OpenCV. The only difference is the PIL.Image.Image class has an attribute size to access the (width, height) of the image." }, { "code": null, "e": 5820, "s": 5808, "text": "The result:" }, { "code": null, "e": 5927, "s": 5820, "text": "Notice how the show method opens the operating system's default program for viewing the image's file type." }, { "code": null, "e": 6047, "s": 5927, "text": "Now we have a function for resizing images, it’s time to bring it full circle with an interface for running the resize." }, { "code": null, "e": 6173, "s": 6047, "text": "Resizing one image is fine. But if we are going through all this trouble, we want the ability to process images in bulk, too." }, { "code": null, "e": 6268, "s": 6173, "text": "The interface we are going to build will be the simplest one possible: a command line utility." }, { "code": null, "e": 6395, "s": 6268, "text": "The Pallets Project is the community of geniuses behind Flask, the Jinja template engine, and relevant to us right now: Click." }, { "code": null, "e": 6413, "s": 6395, "text": "pip install click" }, { "code": null, "e": 6648, "s": 6413, "text": "Click is a library for making command line programs. It is way better than using plain argparse or whipping up some if-then logic in the if __name__ == '__main__': statement. So, we're going to use Click to decorate our image resizer." }, { "code": null, "e": 6715, "s": 6648, "text": "Here is the full script for resizing images from the command line!" }, { "code": null, "e": 6837, "s": 6715, "text": "The command line program runs from the entrypoint function main. Arguments are passed to main by click.option decorators:" }, { "code": null, "e": 7110, "s": 6837, "text": "pattern takes a Python / RE2 style string to locate the image or images relative to the directory where the script is running. --pattern=\"../catpics/*.png\" will go up one level and find the catpics folder, and return any files in that folder with the .png image extension." }, { "code": null, "e": 7494, "s": 7110, "text": "scale takes a number, float or integer, and passes this to the resize function. This script is simple, and that means no data validation. Bonus if you add to the code, checking scale is a number between let's say, 5 and 99 (reasonable down-scaling parameters). As it stands right now, you can pass -s \"chicken nuggets\" and an Exception won't be thrown until Pillow stops the program." }, { "code": null, "e": 7601, "s": 7494, "text": "quiet is an option argument if you do not want text printing to standard out while the program is running." }, { "code": null, "e": 7640, "s": 7601, "text": "Run the program from the command line:" }, { "code": null, "e": 7675, "s": 7640, "text": "python resize.py -s 35 -p \"./*jpg\"" }, { "code": null, "e": 7683, "s": 7675, "text": "Result:" }, { "code": null, "e": 7769, "s": 7683, "text": "$ py resize.py -p \"checkers.jpg\" -s 90resized image saved to checkers_90_810x810.jpg." }, { "code": null, "e": 7790, "s": 7769, "text": "Checking the folder:" }, { "code": null, "e": 7932, "s": 7790, "text": "$ ls -lh checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg" }, { "code": null, "e": 8060, "s": 7932, "text": "Nice! So the program downsized the image, gave it a descriptive label, and we can see the file size went from ~362KB to ~231KB!" }, { "code": null, "e": 8139, "s": 8060, "text": "Just to see the program working on multiple files at once, we’ll run it again:" }, { "code": null, "e": 8292, "s": 8139, "text": "$ py resize.py --pattern=\"checkers*\" --scale=20resized image saved to checkers_20_180x180.jpg.resized image saved to checkers_90_810x810_20_162x162.jpg." }, { "code": null, "e": 8313, "s": 8292, "text": "And the file system:" }, { "code": null, "e": 8599, "s": 8313, "text": "$ ll -h checkers*-rw-r--r-- 1 nicho 197609 362K Aug 15 13:13 checkers.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_20_180x180.jpg-rw-r--r-- 1 nicho 197609 231K Aug 15 23:56 checkers_90_810x810.jpg-rw-r--r-- 1 nicho 197609 1.8K Aug 16 00:23 checkers_90_810x810_20_162x162.jpg" }, { "code": null, "e": 8762, "s": 8599, "text": "Okay, running the program recursively is only for crazy people, but it shows you can run on any number of images matching the pattern all at once. Go, automation!" }, { "code": null, "e": 8768, "s": 8762, "text": "Bonus" }, { "code": null, "e": 9072, "s": 8768, "text": "Click is an amazing tool. It can wrap a function and run in a module “the normal way” from an if __name__ == '__main__': statement. (And actually, it doesn’t even need that; you can just define and decorate the function you want to run.) But where it really shines is installing the script as a package." }, { "code": null, "e": 9137, "s": 9072, "text": "That is done with the setuptools library that comes with Python." }, { "code": null, "e": 9158, "s": 9137, "text": "Here is my setup.py." }, { "code": null, "e": 9217, "s": 9158, "text": "Build the executables / wrap the package with the command:" }, { "code": null, "e": 9234, "s": 9217, "text": "pip install -e ." }, { "code": null, "e": 9460, "s": 9234, "text": "Now you can invoke the script without using the python command. Also–as a bonus bonus–if you add the new executable to a folder in your PATH, you can call this program from anywhere on your computer like resize -p *jpg -s 75!" }, { "code": null, "e": 9910, "s": 9460, "text": "This tutorial bounced around quite a bit: first going over some of the third party Python libraries for image manipulation. Then building an image from scratch using Python to understand a little more about what an image actually is. Then, choosing one of the options and building a script to downscale images while keeping their proportions. And, finally–inhales–putting that all in a command line utility accepting configurable options with click." }, { "code": null, "e": 9956, "s": 9910, "text": "A few more sentences and I’m done, I promise." }, { "code": null, "e": 10097, "s": 9956, "text": "I just wanted to say: there is a reason as to why I covered all these topics in one go with you. And that reason is not because I have ADHD." }, { "code": null, "e": 10352, "s": 10097, "text": "It’s because programming ideas need to close the loop from idea to execution. A one-off concept on how to do something in Python is fine... but at the end of the day, a programming language is a tool. It needs to help us get stuff done to have any value." }, { "code": null, "e": 10614, "s": 10352, "text": "When you start to feel tutorials are overwhelming you with “yet another thing you have to learn”–it means it’s time to take a break from reading, and start coding on some small project. Something you can complete in one sitting, and feel you have made progress." } ]
Hands-On PCA Data Preprocessing Series. Part I: Scaling Transformers | by Kefei Mo | Towards Data Science
In this series, we will explore the combination of scaling data and the PCA. We would like to see how we can better prepare data for machine learning tasks whenever we come across a new dataset. The journey is composed of three parts. Part I: Scalers and PCA Part II: Meet outliers Part III: Categorical data encoding Review briefly the background of scalers and PCAIntroduce the dataset to work on and the taskPerform scaling-transformation on the datasetConduct PCA on the scaling-transformed dataset and evaluate the performance Review briefly the background of scalers and PCA Introduce the dataset to work on and the task Perform scaling-transformation on the dataset Conduct PCA on the scaling-transformed dataset and evaluate the performance Understand the importance of scalers and their close relationship with PCA Choose scalers wisely Make relevant and pretty visualization :) Before you start the reading, we definitely recommend you to play with the notebook (available on Colab and Github. Please find the links at the end of this post.) As you’ve already known, PCA is sensible to the scale of a dataset, hence getting each feature to a reasonable scale is crucial to PCA. In this part, we are going to see how different scalers can affect the PCA results. This post is inspired by this tutorial from Scikit-Learn’s document. You will see us testing different scalers using the same wine dataset, and passing the differently scaled data to the PCA step. This little toy set demonstrate the power of the combination of scaler + PCA, perhaps you would like to have it in your own tool box. Before diving into more details, we would like to make a brief introduction about the PCA, for the sake of completeness of our journey. Readers who have already understood the maths behind will feel free to jump directly to the next section. PCA is the abbreviation of “principal component analysis”, one of its main functionalities is to reduce the dimension (columns) of a dataset. And it is done by singular value decomposition (SVD) of linear algebra. Intuitively, data are in the form of a matrix, whose columns are the axes of high dimensional space. Data points represented with such axis are sometimes hard for machine learning models to explore. What SVD does is to find a smarter representation of the dataset (by the linear combination of the original axes). The data expressed by the new abstract axis are more model-friendly. A few more words: the new set of axes are mutually orthogonal (even better, orthonormal). This property can be particularly lovely for tree-based models. The new set of axes is in the order of their ability to represent the dataset’s information or variability Why do we need scaler? Imagine a dataset of house prices, containing features like the number of rooms, the area, and the price of individual apartments. The variability of these three columns is of vast difference: the maximum difference in the number of rooms can hardly exceed ten rooms, that is of order 1; the maximum difference in the area of an apartment can be of order 100 squared-feet; and the variance in the prices can easily reach the order 10K. What does scaler have anything to do with PCA? If we are to apply PCA on such a dataset whose variability of columns differs in order, the effect of those relatively “smooth” features will be totally overwhelmed by the most furious one (the price in this example). To remedy the problem, we scale the data. There are a bunch of different scalers available with one-line code in SciKit-Learn, like the most commonly used standard scaler and min-max scaler, and other non-linear scalers. In this blog post, we are interested in testing all these available scalers before applying PCA, and see how they act with PCA. If you are interested, here is a detailed demonstration of all scalers tested in this post. Let’s dive in. First, we will need some preparation codes. We will use the wine data as follows. The wine dataset is a legend dataset. The data is the results of a chemical analysis of wines grown in the same region in Italy by three different cultivators. There are thirteen different measurements taken for different constituents found in the three types(origins) of wine. The dataset contains only numerical features. Our goal is to figure out the target labels (the origins), using the thirteen different measurements. First, let’s take a quick look at the data. # note: the code in this post is mainly for illustration purpose. More details, please refer to the original notebook. link at the end of the blog.df_wine.head() df_wine.describe() We kindly invite you to notice the difference in the order of the variability of features: “nonflavanoid_phenols” has a standard deviation of 0.4 while “proline” has 746. We will see later that, without any scaling of the dataset, the result from PCA will be highly biased by those features having huge variance. The dataset’s target column contains three labels so that it can be a multi-class classification task. Here we mimic semi-supervised and unsupervised learning situations by masking out a different amount of the true labels. The reason why we do this additional step will be clear very soon. Let’s first visualize the data, just to get some insight. The data is very clean. And all the features are numerical variables. So we don’t have any tedious data cleaning work to do. Using seaborn’s pairplot and box plot would do reveal the dataset pretty well. fig, axes = plt.subplots(nrows=1, ncols=len(df_features.columns), figsize=(len(df_features.columns)*2,4))for index, col in enumerate(df_features.columns): ax = axes[index] sns.boxplot(y=df_wine.loc[:,col], x=df_wine.loc[:,'target_original'], palette=customer_palette, ax=ax) ax.set_ylabel(ax.get_ylabel(), fontsize='x-large') ax.set_xlabel("")plt.tight_layout(pad=0.5)plt.show() g = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_original', corner=True, palette=customer_palette, hue_order=target_order) # target_large_missinngg = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_large_missinng', corner=True, palette=customer_palette, hue_order=target_order) # target_all_missinngg = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_all_missinng', corner=True, palette=customer_palette, hue_order=target_order) You might be wondering why visualizing the same data three times with just the different colors. We challenge you to distinguish three different target classes in three scenarios. Scenario no.1: with color aid (the first pair plot) Scenario no.2: with weak color aid (the second pair plot) Scenario no.3: no color aid (the last pair plot). The point here is that it becomes very hard for human eyes to distinguish different target classes without target labels or only a limited number of labels (Note: the scenario without target labels is similar to an unsupervised learning situation; the scenario with a limited number of labels is similar to a semi-supervised learning situation). While humans may fail to see higher dimensional interaction between features, machine learning models may find some patterns. Yet why not try to represent the data in a more intelligent way by, for example, a proper scaler followed by the PCA? Here we will transform the dataset using all eight different scalers available in SciKit-Learn’s preprocessing subclass. We are not paying much attention to tuning the scalers’ hyper-parameters. We plot the scatter plots of the PCA’s first two components of the transformed dataset, always keep the spirit of reducing the color aid progressively. # customer visualization function# show scatter of 1st and 2nd PCA componentpca_scatter_plot(X_pca_dict, y_train.iloc[:,1:]) Don’t get lost in the abundance of the scatter plots. Let’s take a closer look at the ones with color aid. We’d like to conclude that, with this dataset, it’s better to scale the data, no matter which scaler we choose. But there is one exception: the normalizer. The normalizer scales data in a weird way: row-wise instead of column-wise. We are unsure of when such a scaler might be useful, but we would love to discuss with you about when to use it. If you wonder why scaled datasets make each class more distinguishable than unscaled data. We are glad you asked. The reason is that the scaled variables can be compared equally. On the contrary, the importance of the unscaled features seen by the machine learning models is highly affected by their scales. Here is a little exercise for readers who have the math knowledge about the PCA. The clusters of different classes don’t always appear in the same order, say from left to right being red, blue, and green; it can be green, blue, and red. Why does such a permutation phenomenon occur? Let’s move on to investigate more about PCA acting on a differently scaled dataset. Below are box plots of each feature after PCA, different scalers are distinguished row-wise. # customer visualization function show PCA componentspca_box_plot(X_pca_dict, df_target.loc[:,'target_original']) Again, without any transformation, almost all the interesting information concentrates on the first component, leaving little variance to the rest of the space. We would claim that the most important ingredient of the first component is “proline” from the original dataset. Indeed the behavior of the boxes is almost identical to that of the boxes plotted for “proline” using the original feature space above. If we look at other scalers (except the normalizer), we can see the trend of boxes bouncing less and less when going from the first component (i.e., the most informative) to the last (i.e., the least informative). More interestingly, almost all scalers result in a cut-off effect on the third component. At this stage, we may be confident enough that the first two components are representative. We can explore even a little further to check the covariance matrices. Since PCA directly works on a covariance matrix and output the principal components. That’s the very beginning of the story. Let’s visualize the covariance matrices by Seaborn’s heatmap function. An important note: we usually use heatmap to show Pearson correlation coefficient matrix (CC matrix), but there is a key difference between these two matrices: the values in a covariance matrix is not necessarily between (-1,1), and the values on diagonal are not always 1. That’s why we plot the diagonal values even using lower triangle heatmap. trans_heat_plot_abs(X_trans_dict, y_axis_labels=df_features.columns) At this point, the heatmap might not be very intuitive comparing to the scatter plots and/or the box plots because the label information does not get into the heatmap. Also, the fine gradient of some colorbars makes some heatmaps very similar to each other. Yet, we do have a hint from these heatmaps of how well a matrix may adapt to the PCA. A rule of thumb is, the more colorful the heatmap, the better the PCA result. Normally PCA doesn’t like a plain-looking heatmap and would output less interesting principal components. In our example, since “proline” is the one that stands out, PCA will have all eyes on it. And this is consistent with our analysis earlier. Another plain-looking one is normalizer transformed data. From the heatmap, we might guess that the ONE component from PCA would be largely from “magnesium”; hence the dull result is given by normalizer + PCA. # plot the explained_variance cumsum using previously calculated PCA instances.pca_plot_cumsum(instance_pca_dict) We are more or less happy with the preprocessing results, by seeing the first two dimensions of the new aspect of the feature space, found by PCA. However, are the clustering algorithms that can see higher dimensional interactions favor the same transformed matrices as we do? Let’s cluster the data using machine learning clustering models. One advantage we have when doing clustering tasks on the labeled dataset is, we know the correct number of classes. Next, we will see how well the k-means agrees with the true labels. Here we adopted the first metric for the blog: V-measure score. We would not go into the details to talk about this index; all you need to know is: The V-measure score is bounded in the range [0,1]: values close to 0 are bad, while 1.0 stands for a perfect match. df_scores We are comparing three scenarios: clustering with two original features, the two most informative PCA components, and the total feature set. We chose two features or components to keep the consistency with the previous scatter plots. While more columns might reveal more thoroughly the dataset’s information, we think that two dimensions, at least to begin with, are good enough. Let’s take a closer look at the above table. Firstly, let’s focus on the last column, which contains V-measure scores using the entire dataset. It’s always better to scale the data, no matter which scaler we choose. (Except the “Normalizer”) Secondly, for the original aspect of the feature space, it’s always better to use the entire dataset. And it seems not a good idea to choose a subset of features that “seems” to illustrate better the clusters. (Just look at the comparison between the first and the third columns). On the other hand, it is a different story for PCA transformed data. Sometimes, it results in more reasonable clusters with merely a few of the components than using all of them. (Take a look at the comparison between the second and the third columns). Even though in some of the tests, the first-2-component choice does not outperform the totality, there is a close match in terms of the V-measure score between the two choices. (since here we are comparing the calculation sources of 2-column matrices vs. 13-column matrices.) And lastly, looking at the second column, we find that the most suitable scalers for this single task are the two non-linear ones plus the standard scaler. For this reason, you might want to try out more scalers by doing simple tests before applying directly to the most commonly used standard scaler. We’d like to have a few more words on the less-is-more phenomenon shown by PCA. It’s often argued that throwing away information from the original dataset is not wise; it is sometimes very dangerous to do so. Yet PCA reveals the most important patterns inside the data matrix while filtering out some details. Such details could be nothing but noise. So taking the first several PCA components not only helps reduce the conditionality but also smoothens the information and makes things clearer. kmeans = KMeans(n_clusters=3, random_state=RANDOM_STATE)pca_cluster_contour_plot(X_pca_dict,y_train, kmeans) In this post, we have compared the results of PCA acting on differently scaled data by showing the scatter plots. Visually we can see that the combination does carve the pattern of the dataset clearer than no preprocessing. Before applying PCA, the takeaway would always check the variance of each feature in the dataset, and if there is a large gap between the variances, scale the data with a proper scaler. Depending on your task, the definition of “proper” can vary. Next time, we will be stretching the limits of this scaler + PCA combination, by bringing in synthetic outliers and categorical features. I hope you like this post. Please feel free to leave comments. Announcement: this series is a colaboration of Kefei Mo and Siyun Wang Siyun Wang. 1st release: 06/08/2020.
[ { "code": null, "e": 407, "s": 172, "text": "In this series, we will explore the combination of scaling data and the PCA. We would like to see how we can better prepare data for machine learning tasks whenever we come across a new dataset. The journey is composed of three parts." }, { "code": null, "e": 431, "s": 407, "text": "Part I: Scalers and PCA" }, { "code": null, "e": 454, "s": 431, "text": "Part II: Meet outliers" }, { "code": null, "e": 490, "s": 454, "text": "Part III: Categorical data encoding" }, { "code": null, "e": 704, "s": 490, "text": "Review briefly the background of scalers and PCAIntroduce the dataset to work on and the taskPerform scaling-transformation on the datasetConduct PCA on the scaling-transformed dataset and evaluate the performance" }, { "code": null, "e": 753, "s": 704, "text": "Review briefly the background of scalers and PCA" }, { "code": null, "e": 799, "s": 753, "text": "Introduce the dataset to work on and the task" }, { "code": null, "e": 845, "s": 799, "text": "Perform scaling-transformation on the dataset" }, { "code": null, "e": 921, "s": 845, "text": "Conduct PCA on the scaling-transformed dataset and evaluate the performance" }, { "code": null, "e": 996, "s": 921, "text": "Understand the importance of scalers and their close relationship with PCA" }, { "code": null, "e": 1018, "s": 996, "text": "Choose scalers wisely" }, { "code": null, "e": 1060, "s": 1018, "text": "Make relevant and pretty visualization :)" }, { "code": null, "e": 1224, "s": 1060, "text": "Before you start the reading, we definitely recommend you to play with the notebook (available on Colab and Github. Please find the links at the end of this post.)" }, { "code": null, "e": 1444, "s": 1224, "text": "As you’ve already known, PCA is sensible to the scale of a dataset, hence getting each feature to a reasonable scale is crucial to PCA. In this part, we are going to see how different scalers can affect the PCA results." }, { "code": null, "e": 1775, "s": 1444, "text": "This post is inspired by this tutorial from Scikit-Learn’s document. You will see us testing different scalers using the same wine dataset, and passing the differently scaled data to the PCA step. This little toy set demonstrate the power of the combination of scaler + PCA, perhaps you would like to have it in your own tool box." }, { "code": null, "e": 2017, "s": 1775, "text": "Before diving into more details, we would like to make a brief introduction about the PCA, for the sake of completeness of our journey. Readers who have already understood the maths behind will feel free to jump directly to the next section." }, { "code": null, "e": 2614, "s": 2017, "text": "PCA is the abbreviation of “principal component analysis”, one of its main functionalities is to reduce the dimension (columns) of a dataset. And it is done by singular value decomposition (SVD) of linear algebra. Intuitively, data are in the form of a matrix, whose columns are the axes of high dimensional space. Data points represented with such axis are sometimes hard for machine learning models to explore. What SVD does is to find a smarter representation of the dataset (by the linear combination of the original axes). The data expressed by the new abstract axis are more model-friendly." }, { "code": null, "e": 2875, "s": 2614, "text": "A few more words: the new set of axes are mutually orthogonal (even better, orthonormal). This property can be particularly lovely for tree-based models. The new set of axes is in the order of their ability to represent the dataset’s information or variability" }, { "code": null, "e": 3334, "s": 2875, "text": "Why do we need scaler? Imagine a dataset of house prices, containing features like the number of rooms, the area, and the price of individual apartments. The variability of these three columns is of vast difference: the maximum difference in the number of rooms can hardly exceed ten rooms, that is of order 1; the maximum difference in the area of an apartment can be of order 100 squared-feet; and the variance in the prices can easily reach the order 10K." }, { "code": null, "e": 3641, "s": 3334, "text": "What does scaler have anything to do with PCA? If we are to apply PCA on such a dataset whose variability of columns differs in order, the effect of those relatively “smooth” features will be totally overwhelmed by the most furious one (the price in this example). To remedy the problem, we scale the data." }, { "code": null, "e": 4040, "s": 3641, "text": "There are a bunch of different scalers available with one-line code in SciKit-Learn, like the most commonly used standard scaler and min-max scaler, and other non-linear scalers. In this blog post, we are interested in testing all these available scalers before applying PCA, and see how they act with PCA. If you are interested, here is a detailed demonstration of all scalers tested in this post." }, { "code": null, "e": 4137, "s": 4040, "text": "Let’s dive in. First, we will need some preparation codes. We will use the wine data as follows." }, { "code": null, "e": 4607, "s": 4137, "text": "The wine dataset is a legend dataset. The data is the results of a chemical analysis of wines grown in the same region in Italy by three different cultivators. There are thirteen different measurements taken for different constituents found in the three types(origins) of wine. The dataset contains only numerical features. Our goal is to figure out the target labels (the origins), using the thirteen different measurements. First, let’s take a quick look at the data." }, { "code": null, "e": 4769, "s": 4607, "text": "# note: the code in this post is mainly for illustration purpose. More details, please refer to the original notebook. link at the end of the blog.df_wine.head()" }, { "code": null, "e": 4788, "s": 4769, "text": "df_wine.describe()" }, { "code": null, "e": 5101, "s": 4788, "text": "We kindly invite you to notice the difference in the order of the variability of features: “nonflavanoid_phenols” has a standard deviation of 0.4 while “proline” has 746. We will see later that, without any scaling of the dataset, the result from PCA will be highly biased by those features having huge variance." }, { "code": null, "e": 5450, "s": 5101, "text": "The dataset’s target column contains three labels so that it can be a multi-class classification task. Here we mimic semi-supervised and unsupervised learning situations by masking out a different amount of the true labels. The reason why we do this additional step will be clear very soon. Let’s first visualize the data, just to get some insight." }, { "code": null, "e": 5654, "s": 5450, "text": "The data is very clean. And all the features are numerical variables. So we don’t have any tedious data cleaning work to do. Using seaborn’s pairplot and box plot would do reveal the dataset pretty well." }, { "code": null, "e": 6045, "s": 5654, "text": "fig, axes = plt.subplots(nrows=1, ncols=len(df_features.columns), figsize=(len(df_features.columns)*2,4))for index, col in enumerate(df_features.columns): ax = axes[index] sns.boxplot(y=df_wine.loc[:,col], x=df_wine.loc[:,'target_original'], palette=customer_palette, ax=ax) ax.set_ylabel(ax.get_ylabel(), fontsize='x-large') ax.set_xlabel(\"\")plt.tight_layout(pad=0.5)plt.show()" }, { "code": null, "e": 6269, "s": 6045, "text": "g = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_original', corner=True, palette=customer_palette, hue_order=target_order)" }, { "code": null, "e": 6526, "s": 6269, "text": "# target_large_missinngg = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_large_missinng', corner=True, palette=customer_palette, hue_order=target_order)" }, { "code": null, "e": 6779, "s": 6526, "text": "# target_all_missinngg = sns.pairplot(data=df_wine, vars=df_features.columns, hue='target_all_missinng', corner=True, palette=customer_palette, hue_order=target_order)" }, { "code": null, "e": 6876, "s": 6779, "text": "You might be wondering why visualizing the same data three times with just the different colors." }, { "code": null, "e": 6959, "s": 6876, "text": "We challenge you to distinguish three different target classes in three scenarios." }, { "code": null, "e": 7011, "s": 6959, "text": "Scenario no.1: with color aid (the first pair plot)" }, { "code": null, "e": 7069, "s": 7011, "text": "Scenario no.2: with weak color aid (the second pair plot)" }, { "code": null, "e": 7119, "s": 7069, "text": "Scenario no.3: no color aid (the last pair plot)." }, { "code": null, "e": 7465, "s": 7119, "text": "The point here is that it becomes very hard for human eyes to distinguish different target classes without target labels or only a limited number of labels (Note: the scenario without target labels is similar to an unsupervised learning situation; the scenario with a limited number of labels is similar to a semi-supervised learning situation)." }, { "code": null, "e": 7709, "s": 7465, "text": "While humans may fail to see higher dimensional interaction between features, machine learning models may find some patterns. Yet why not try to represent the data in a more intelligent way by, for example, a proper scaler followed by the PCA?" }, { "code": null, "e": 8056, "s": 7709, "text": "Here we will transform the dataset using all eight different scalers available in SciKit-Learn’s preprocessing subclass. We are not paying much attention to tuning the scalers’ hyper-parameters. We plot the scatter plots of the PCA’s first two components of the transformed dataset, always keep the spirit of reducing the color aid progressively." }, { "code": null, "e": 8181, "s": 8056, "text": "# customer visualization function# show scatter of 1st and 2nd PCA componentpca_scatter_plot(X_pca_dict, y_train.iloc[:,1:])" }, { "code": null, "e": 8633, "s": 8181, "text": "Don’t get lost in the abundance of the scatter plots. Let’s take a closer look at the ones with color aid. We’d like to conclude that, with this dataset, it’s better to scale the data, no matter which scaler we choose. But there is one exception: the normalizer. The normalizer scales data in a weird way: row-wise instead of column-wise. We are unsure of when such a scaler might be useful, but we would love to discuss with you about when to use it." }, { "code": null, "e": 8941, "s": 8633, "text": "If you wonder why scaled datasets make each class more distinguishable than unscaled data. We are glad you asked. The reason is that the scaled variables can be compared equally. On the contrary, the importance of the unscaled features seen by the machine learning models is highly affected by their scales." }, { "code": null, "e": 9224, "s": 8941, "text": "Here is a little exercise for readers who have the math knowledge about the PCA. The clusters of different classes don’t always appear in the same order, say from left to right being red, blue, and green; it can be green, blue, and red. Why does such a permutation phenomenon occur?" }, { "code": null, "e": 9401, "s": 9224, "text": "Let’s move on to investigate more about PCA acting on a differently scaled dataset. Below are box plots of each feature after PCA, different scalers are distinguished row-wise." }, { "code": null, "e": 9515, "s": 9401, "text": "# customer visualization function show PCA componentspca_box_plot(X_pca_dict, df_target.loc[:,'target_original'])" }, { "code": null, "e": 9925, "s": 9515, "text": "Again, without any transformation, almost all the interesting information concentrates on the first component, leaving little variance to the rest of the space. We would claim that the most important ingredient of the first component is “proline” from the original dataset. Indeed the behavior of the boxes is almost identical to that of the boxes plotted for “proline” using the original feature space above." }, { "code": null, "e": 10321, "s": 9925, "text": "If we look at other scalers (except the normalizer), we can see the trend of boxes bouncing less and less when going from the first component (i.e., the most informative) to the last (i.e., the least informative). More interestingly, almost all scalers result in a cut-off effect on the third component. At this stage, we may be confident enough that the first two components are representative." }, { "code": null, "e": 10517, "s": 10321, "text": "We can explore even a little further to check the covariance matrices. Since PCA directly works on a covariance matrix and output the principal components. That’s the very beginning of the story." }, { "code": null, "e": 10588, "s": 10517, "text": "Let’s visualize the covariance matrices by Seaborn’s heatmap function." }, { "code": null, "e": 10936, "s": 10588, "text": "An important note: we usually use heatmap to show Pearson correlation coefficient matrix (CC matrix), but there is a key difference between these two matrices: the values in a covariance matrix is not necessarily between (-1,1), and the values on diagonal are not always 1. That’s why we plot the diagonal values even using lower triangle heatmap." }, { "code": null, "e": 11005, "s": 10936, "text": "trans_heat_plot_abs(X_trans_dict, y_axis_labels=df_features.columns)" }, { "code": null, "e": 11263, "s": 11005, "text": "At this point, the heatmap might not be very intuitive comparing to the scatter plots and/or the box plots because the label information does not get into the heatmap. Also, the fine gradient of some colorbars makes some heatmaps very similar to each other." }, { "code": null, "e": 11883, "s": 11263, "text": "Yet, we do have a hint from these heatmaps of how well a matrix may adapt to the PCA. A rule of thumb is, the more colorful the heatmap, the better the PCA result. Normally PCA doesn’t like a plain-looking heatmap and would output less interesting principal components. In our example, since “proline” is the one that stands out, PCA will have all eyes on it. And this is consistent with our analysis earlier. Another plain-looking one is normalizer transformed data. From the heatmap, we might guess that the ONE component from PCA would be largely from “magnesium”; hence the dull result is given by normalizer + PCA." }, { "code": null, "e": 11997, "s": 11883, "text": "# plot the explained_variance cumsum using previously calculated PCA instances.pca_plot_cumsum(instance_pca_dict)" }, { "code": null, "e": 12339, "s": 11997, "text": "We are more or less happy with the preprocessing results, by seeing the first two dimensions of the new aspect of the feature space, found by PCA. However, are the clustering algorithms that can see higher dimensional interactions favor the same transformed matrices as we do? Let’s cluster the data using machine learning clustering models." }, { "code": null, "e": 12523, "s": 12339, "text": "One advantage we have when doing clustering tasks on the labeled dataset is, we know the correct number of classes. Next, we will see how well the k-means agrees with the true labels." }, { "code": null, "e": 12787, "s": 12523, "text": "Here we adopted the first metric for the blog: V-measure score. We would not go into the details to talk about this index; all you need to know is: The V-measure score is bounded in the range [0,1]: values close to 0 are bad, while 1.0 stands for a perfect match." }, { "code": null, "e": 12797, "s": 12787, "text": "df_scores" }, { "code": null, "e": 13177, "s": 12797, "text": "We are comparing three scenarios: clustering with two original features, the two most informative PCA components, and the total feature set. We chose two features or components to keep the consistency with the previous scatter plots. While more columns might reveal more thoroughly the dataset’s information, we think that two dimensions, at least to begin with, are good enough." }, { "code": null, "e": 13222, "s": 13177, "text": "Let’s take a closer look at the above table." }, { "code": null, "e": 13419, "s": 13222, "text": "Firstly, let’s focus on the last column, which contains V-measure scores using the entire dataset. It’s always better to scale the data, no matter which scaler we choose. (Except the “Normalizer”)" }, { "code": null, "e": 13700, "s": 13419, "text": "Secondly, for the original aspect of the feature space, it’s always better to use the entire dataset. And it seems not a good idea to choose a subset of features that “seems” to illustrate better the clusters. (Just look at the comparison between the first and the third columns)." }, { "code": null, "e": 14229, "s": 13700, "text": "On the other hand, it is a different story for PCA transformed data. Sometimes, it results in more reasonable clusters with merely a few of the components than using all of them. (Take a look at the comparison between the second and the third columns). Even though in some of the tests, the first-2-component choice does not outperform the totality, there is a close match in terms of the V-measure score between the two choices. (since here we are comparing the calculation sources of 2-column matrices vs. 13-column matrices.)" }, { "code": null, "e": 14531, "s": 14229, "text": "And lastly, looking at the second column, we find that the most suitable scalers for this single task are the two non-linear ones plus the standard scaler. For this reason, you might want to try out more scalers by doing simple tests before applying directly to the most commonly used standard scaler." }, { "code": null, "e": 15027, "s": 14531, "text": "We’d like to have a few more words on the less-is-more phenomenon shown by PCA. It’s often argued that throwing away information from the original dataset is not wise; it is sometimes very dangerous to do so. Yet PCA reveals the most important patterns inside the data matrix while filtering out some details. Such details could be nothing but noise. So taking the first several PCA components not only helps reduce the conditionality but also smoothens the information and makes things clearer." }, { "code": null, "e": 15136, "s": 15027, "text": "kmeans = KMeans(n_clusters=3, random_state=RANDOM_STATE)pca_cluster_contour_plot(X_pca_dict,y_train, kmeans)" }, { "code": null, "e": 15607, "s": 15136, "text": "In this post, we have compared the results of PCA acting on differently scaled data by showing the scatter plots. Visually we can see that the combination does carve the pattern of the dataset clearer than no preprocessing. Before applying PCA, the takeaway would always check the variance of each feature in the dataset, and if there is a large gap between the variances, scale the data with a proper scaler. Depending on your task, the definition of “proper” can vary." }, { "code": null, "e": 15745, "s": 15607, "text": "Next time, we will be stretching the limits of this scaler + PCA combination, by bringing in synthetic outliers and categorical features." }, { "code": null, "e": 15808, "s": 15745, "text": "I hope you like this post. Please feel free to leave comments." } ]
Repeated DNA Sequences in C++
Suppose we have a DNA sequence. As we know, all DNA is composed of a series of nucleotides abbreviated such as A, C, G, and T, for example: "ACGAATTCCG". When we are studying DNA, it is sometimes useful to identify repeated sequences within the DNA. We have to write one method to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. So if the input is like “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”, then the output will be ["AAAAACCCCC", "CCCCCAAAAA"]. To solve this, we will follow these steps − Define an array ret, n := size of s, create two sets called visited and visited2 Define an array ret, n := size of s, create two sets called visited and visited2 define a map called bitVal. define a map called bitVal. Store corresponding values for ACGT like 0123 into butVal. Store corresponding values for ACGT like 0123 into butVal. mask := 0 mask := 0 for i in range 0 to n – 1mask := mask * 4mask := mast OR bitVal[s[i]]mask := mask AND FFFFFif i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2.insert mask into visited for i in range 0 to n – 1 mask := mask * 4 mask := mask * 4 mask := mast OR bitVal[s[i]] mask := mast OR bitVal[s[i]] mask := mask AND FFFFF mask := mask AND FFFFF if i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2. if i < 9, then just continue to the next iteration insert substring form index i – 9 to 9, into ret insert substring form index i – 9 to 9, into ret insert mark into visited2. insert mark into visited2. insert mask into visited insert mask into visited return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } typedef long long int lli; class Solution { public: vector<string>findRepeatedDnaSequences(string s) { vector <string> ret; int n = s.size(); set <int> visited; set <int> visited2; map <char, int> bitVal; bitVal['A'] = 0; bitVal['C'] = 1; bitVal['G'] = 2; bitVal['T'] = 3; lli mask = 0; for(int i = 0; i < n; i++){ mask <<= 2; mask |= bitVal[s[i]]; mask &= 0xfffff; if(i < 9) continue; if(visited.count(mask) && !visited2.count(mask)){ ret.push_back(s.substr(i - 9, 10)); visited2.insert(mask); } visited.insert(mask); } return ret; } }; main(){ Solution ob; print_vector(ob.findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT")); } "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" [AAAAACCCCC, CCCCCAAAAA, ]
[ { "code": null, "e": 1312, "s": 1062, "text": "Suppose we have a DNA sequence. As we know, all DNA is composed of a series of nucleotides abbreviated such as A, C, G, and T, for example: \"ACGAATTCCG\". When we are studying DNA, it is sometimes useful to identify repeated sequences within the DNA." }, { "code": null, "e": 1439, "s": 1312, "text": "We have to write one method to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule." }, { "code": null, "e": 1553, "s": 1439, "text": "So if the input is like “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”, then the output will be [\"AAAAACCCCC\", \"CCCCCAAAAA\"]." }, { "code": null, "e": 1597, "s": 1553, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1678, "s": 1597, "text": "Define an array ret, n := size of s, create two sets called visited and visited2" }, { "code": null, "e": 1759, "s": 1678, "text": "Define an array ret, n := size of s, create two sets called visited and visited2" }, { "code": null, "e": 1787, "s": 1759, "text": "define a map called bitVal." }, { "code": null, "e": 1815, "s": 1787, "text": "define a map called bitVal." }, { "code": null, "e": 1874, "s": 1815, "text": "Store corresponding values for ACGT like 0123 into butVal." }, { "code": null, "e": 1933, "s": 1874, "text": "Store corresponding values for ACGT like 0123 into butVal." }, { "code": null, "e": 1943, "s": 1933, "text": "mask := 0" }, { "code": null, "e": 1953, "s": 1943, "text": "mask := 0" }, { "code": null, "e": 2193, "s": 1953, "text": "for i in range 0 to n – 1mask := mask * 4mask := mast OR bitVal[s[i]]mask := mask AND FFFFFif i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2.insert mask into visited" }, { "code": null, "e": 2219, "s": 2193, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 2236, "s": 2219, "text": "mask := mask * 4" }, { "code": null, "e": 2253, "s": 2236, "text": "mask := mask * 4" }, { "code": null, "e": 2282, "s": 2253, "text": "mask := mast OR bitVal[s[i]]" }, { "code": null, "e": 2311, "s": 2282, "text": "mask := mast OR bitVal[s[i]]" }, { "code": null, "e": 2334, "s": 2311, "text": "mask := mask AND FFFFF" }, { "code": null, "e": 2357, "s": 2334, "text": "mask := mask AND FFFFF" }, { "code": null, "e": 2482, "s": 2357, "text": "if i < 9, then just continue to the next iterationinsert substring form index i – 9 to 9, into retinsert mark into visited2." }, { "code": null, "e": 2533, "s": 2482, "text": "if i < 9, then just continue to the next iteration" }, { "code": null, "e": 2582, "s": 2533, "text": "insert substring form index i – 9 to 9, into ret" }, { "code": null, "e": 2631, "s": 2582, "text": "insert substring form index i – 9 to 9, into ret" }, { "code": null, "e": 2658, "s": 2631, "text": "insert mark into visited2." }, { "code": null, "e": 2685, "s": 2658, "text": "insert mark into visited2." }, { "code": null, "e": 2710, "s": 2685, "text": "insert mask into visited" }, { "code": null, "e": 2735, "s": 2710, "text": "insert mask into visited" }, { "code": null, "e": 2746, "s": 2735, "text": "return ret" }, { "code": null, "e": 2757, "s": 2746, "text": "return ret" }, { "code": null, "e": 2829, "s": 2757, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2840, "s": 2829, "text": " Live Demo" }, { "code": null, "e": 3847, "s": 2840, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\ntypedef long long int lli;\nclass Solution {\npublic:\n vector<string>findRepeatedDnaSequences(string s) {\n vector <string> ret;\n int n = s.size();\n set <int> visited;\n set <int> visited2;\n map <char, int> bitVal;\n bitVal['A'] = 0;\n bitVal['C'] = 1;\n bitVal['G'] = 2;\n bitVal['T'] = 3;\n lli mask = 0;\n for(int i = 0; i < n; i++){\n mask <<= 2;\n mask |= bitVal[s[i]];\n mask &= 0xfffff;\n if(i < 9) continue;\n if(visited.count(mask) && !visited2.count(mask)){\n ret.push_back(s.substr(i - 9, 10));\n visited2.insert(mask);\n }\n visited.insert(mask);\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n print_vector(ob.findRepeatedDnaSequences(\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"));\n}" }, { "code": null, "e": 3882, "s": 3847, "text": "\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"" }, { "code": null, "e": 3909, "s": 3882, "text": "[AAAAACCCCC, CCCCCAAAAA, ]" } ]
A guide to basic Exploratory Data Analysis using Pandas. | by Abhishek Kumar | Towards Data Science
It is relatively easy to draw graphs using libraries say Matplotlib or query the data. However, to be able to draw graphs the data has to in a certain format. One of the motivations behind this article is to understand how to prepare data for further processing. The article also discusses on performing basic operations such as querying, sorting and visualising Pandas data frames. Although data can be available in multiple format but for the sake of discussion let us assume the data to be in Comma Separated Value (CSV) format. import pandas as pddf = pd.read_csv("path/to/file.csv") The above syntax is pretty standard and is sufficient most of the times. The default behaviour of read_csv() assumes first line in a CSV file to be column headings and uses it as the heading for the data frame created. However, the following variation dictates to use the first row as a part of data. df = pd.read_csv("path/to/file.csv", header=None) In this case you can explicitly specify column headings as — df = pd.read_csv("path/to/file.csv", names=["Column 1", "Column 2"]) If names parameter is not specified then columns are indexed starting from 0. Once you have read your data, the next step is to make yourself comfortable with the data set. Let’s begin by seeing the number of records in data set. #Assume that the data is stored in a variable dfrowsInData = df.shape[0]colsInData = df.shape[1]#A concise wayrowsInData, colsInData = df.shape Once you know the size of data let’s take a look at how does the data look. You can use the head() function to take a look at the starting rows of the data set. The tail() function is used to look at the bottom rows of the data set. df.head()# The default behaviour of head() is to show the first five rows of the data. You can pass an integer value to view more or less rows. The following variation shows the first 10 row.df.head(10) Having seeing the data let us try to understand the data better. It is really helpful if you know the data type of data stored in a column. It helps you to apply appropriate functions to column. For example, if the column is of float or integer data type then you can apply functions like mean() and max() over them. The info() function returns a summary of data frame along with the data type for each column. df.info() Let’s see different type of data that is stored in the column. df[col].value_counts(dropna=False) The above command will help you to see you the frequency of each item stored in ‘col’. In some cases you might see unwanted values that you want to get rid of, say NaN in case of numbers or empty values in case of strings. Let’s discuss on how to clean the data set in the next section. The most naive approach to clean the data set will be to drop rows which contain unwanted values. Another convincing way is to impute missing data. Let’s see how to handle not a number (NaN) value. #To get the count of null values in each column use the following syntaxdf.isnull().sum()#Dropna removes rows containing NaN values.df.dropna() Instead of dropping the rows you can choose to replace the NaN value with say 0 or replace it by say using the mean of the respective column. #Fill missing values with zerosdf[col].fillna(0, inplace=True)#Fill missing values with column meanmean = df[col].mean()df[col].fillna(mean,inplace=True)# inplace = True parameter modifies the original dataframe. In case inplace = False a new data frame is returned after the necessary operations are applied. Obviously you cannot compute mean for string values, but comparison and regex can be used to find strings of undesired format and replace them with a value of your choice or drop the corresponding row. #There can be multiple ways to drop rows but let's see two ways #The following command replaces strings having a single space character with NaN and then uses dropna() function to remove the rows as discussed earlier.df[col].replace(' ', np.nan, inplace=True)df.dropna()#If you are familiar with regex it can be extremely useful. The following command uses regular expressions to grab a string which is composed of whitespaces (\s in regex refers to whitespace characters) and replaces them with NaN.df[col].replace(r'^\s*$', np.nan, regex=True, inplace=True)df.dropna() If instead of dropping you want to replace the missing string value you can do it as follows — #Replace using strict comparisondf[col].replace(' ', "Some Value", inplace=True)#Replace using regular expressiondf[col].replace(r'^\s*$', "Some Value", regex=True, inplace=True) Assume you expected that a particular field in your CSV to have only integer values but accidentally the column has a string value. In this case you cannot process the column as integer. Let’s see how to handle such situation. You can choose to find the string values and replace it with any suitable value as discussed earlier. Once you have replaced string value you can convert the data type of column as follows — df[col] = pd.to_numeric(df[col]) Once you have finished processing your data, the next step is to extract valuable information from the data. For the sake of discussion let us consider a very small data set comprising of marks of a couple of students. Below is the tabular representation of the CSV data. The basic query is to list students who scored above a certain value. The following query shows all records in which marks scored for Test1 are greater than 15. Apart from the greater than operator other relational operators can also be used such as > =, <, < =, ==, and =!. df.query('Test1 > 15') The following query shows how to perform comparison on string values. There also exists the not equal (!=) operator. The following query retrieves marks for John. df.query('Name == "John"') Apart from basic comparison for string you can also apply functions such as startswith(), endswith() and contains() to filter the data. The following example queries marks for students whose name starts with J. df.query('Name.str.startswith("J")', engine='python') Although, pandas provides ways to filter based on string valued columns but there is nothing more powerful than using regex. The following example retrieves names that begin with A using regex. df.query('Name.str.contains("^A", regex=True)', engine='python') You can also combine multiple conditions using and and or. The following query retrieves record in which students have scored more than 16 marks in the first two tests. df.query('Test1 > 16 and Test2 > 16)') It is not always that you want to compare values with a constant. The following syntax is used to compare corresponding values of two columns and return the rows which satisfy the condition. This query shows list of students who have improved their performance in the second test as compared to the first test. df.query('Test1 < Test2') There is a possibility in which you do not want to see results which comprise of all the columns. Let us take a look on how to conditionally retrieve marks only for Test2. #The following statement shows just the Name and Test2 columns only if test2 marks are more than 15. It doesn't show full rows as earlier.df[['Name', 'Test2']].query('Test2 > 15') The next most common operation is to sort data. Let’s take look at an example to sort students in descending order of marks obtained in Test3. #Let's select only Name and Test3 columns first.temp = df[['Name', 'Test3']]#Now's let's sort by Test3 in ascending order.temp.sort_values(by=['Test3'])#Sorting by Test3 in descending order.temp.sort_values(by=['Test3'], ascending=False) You can use libraries such as Matpoltlib to graph and visualise data which will help to quickly find trends and patterns in data. But for the sake of uniformity let’s use plot() function provided by Pandas dataframe class. A bar chart of ‘Name’ and marks scored in ‘Test1’. df.plot.bar(x='Name', y='Test1') The following graph is a comparison between marks scored by each student in all the three tests. df.plot.bar(x='Name', y=['Test1', 'Test2', 'Test3']) You can certainly draw more informative graphs based on your requirement but to keep the discussion simple let’s wrap it up here.
[ { "code": null, "e": 555, "s": 172, "text": "It is relatively easy to draw graphs using libraries say Matplotlib or query the data. However, to be able to draw graphs the data has to in a certain format. One of the motivations behind this article is to understand how to prepare data for further processing. The article also discusses on performing basic operations such as querying, sorting and visualising Pandas data frames." }, { "code": null, "e": 704, "s": 555, "text": "Although data can be available in multiple format but for the sake of discussion let us assume the data to be in Comma Separated Value (CSV) format." }, { "code": null, "e": 760, "s": 704, "text": "import pandas as pddf = pd.read_csv(\"path/to/file.csv\")" }, { "code": null, "e": 1061, "s": 760, "text": "The above syntax is pretty standard and is sufficient most of the times. The default behaviour of read_csv() assumes first line in a CSV file to be column headings and uses it as the heading for the data frame created. However, the following variation dictates to use the first row as a part of data." }, { "code": null, "e": 1111, "s": 1061, "text": "df = pd.read_csv(\"path/to/file.csv\", header=None)" }, { "code": null, "e": 1172, "s": 1111, "text": "In this case you can explicitly specify column headings as —" }, { "code": null, "e": 1241, "s": 1172, "text": "df = pd.read_csv(\"path/to/file.csv\", names=[\"Column 1\", \"Column 2\"])" }, { "code": null, "e": 1319, "s": 1241, "text": "If names parameter is not specified then columns are indexed starting from 0." }, { "code": null, "e": 1471, "s": 1319, "text": "Once you have read your data, the next step is to make yourself comfortable with the data set. Let’s begin by seeing the number of records in data set." }, { "code": null, "e": 1615, "s": 1471, "text": "#Assume that the data is stored in a variable dfrowsInData = df.shape[0]colsInData = df.shape[1]#A concise wayrowsInData, colsInData = df.shape" }, { "code": null, "e": 1848, "s": 1615, "text": "Once you know the size of data let’s take a look at how does the data look. You can use the head() function to take a look at the starting rows of the data set. The tail() function is used to look at the bottom rows of the data set." }, { "code": null, "e": 2051, "s": 1848, "text": "df.head()# The default behaviour of head() is to show the first five rows of the data. You can pass an integer value to view more or less rows. The following variation shows the first 10 row.df.head(10)" }, { "code": null, "e": 2462, "s": 2051, "text": "Having seeing the data let us try to understand the data better. It is really helpful if you know the data type of data stored in a column. It helps you to apply appropriate functions to column. For example, if the column is of float or integer data type then you can apply functions like mean() and max() over them. The info() function returns a summary of data frame along with the data type for each column." }, { "code": null, "e": 2472, "s": 2462, "text": "df.info()" }, { "code": null, "e": 2535, "s": 2472, "text": "Let’s see different type of data that is stored in the column." }, { "code": null, "e": 2570, "s": 2535, "text": "df[col].value_counts(dropna=False)" }, { "code": null, "e": 2857, "s": 2570, "text": "The above command will help you to see you the frequency of each item stored in ‘col’. In some cases you might see unwanted values that you want to get rid of, say NaN in case of numbers or empty values in case of strings. Let’s discuss on how to clean the data set in the next section." }, { "code": null, "e": 3055, "s": 2857, "text": "The most naive approach to clean the data set will be to drop rows which contain unwanted values. Another convincing way is to impute missing data. Let’s see how to handle not a number (NaN) value." }, { "code": null, "e": 3199, "s": 3055, "text": "#To get the count of null values in each column use the following syntaxdf.isnull().sum()#Dropna removes rows containing NaN values.df.dropna()" }, { "code": null, "e": 3341, "s": 3199, "text": "Instead of dropping the rows you can choose to replace the NaN value with say 0 or replace it by say using the mean of the respective column." }, { "code": null, "e": 3651, "s": 3341, "text": "#Fill missing values with zerosdf[col].fillna(0, inplace=True)#Fill missing values with column meanmean = df[col].mean()df[col].fillna(mean,inplace=True)# inplace = True parameter modifies the original dataframe. In case inplace = False a new data frame is returned after the necessary operations are applied." }, { "code": null, "e": 3853, "s": 3651, "text": "Obviously you cannot compute mean for string values, but comparison and regex can be used to find strings of undesired format and replace them with a value of your choice or drop the corresponding row." }, { "code": null, "e": 4424, "s": 3853, "text": "#There can be multiple ways to drop rows but let's see two ways #The following command replaces strings having a single space character with NaN and then uses dropna() function to remove the rows as discussed earlier.df[col].replace(' ', np.nan, inplace=True)df.dropna()#If you are familiar with regex it can be extremely useful. The following command uses regular expressions to grab a string which is composed of whitespaces (\\s in regex refers to whitespace characters) and replaces them with NaN.df[col].replace(r'^\\s*$', np.nan, regex=True, inplace=True)df.dropna()" }, { "code": null, "e": 4519, "s": 4424, "text": "If instead of dropping you want to replace the missing string value you can do it as follows —" }, { "code": null, "e": 4698, "s": 4519, "text": "#Replace using strict comparisondf[col].replace(' ', \"Some Value\", inplace=True)#Replace using regular expressiondf[col].replace(r'^\\s*$', \"Some Value\", regex=True, inplace=True)" }, { "code": null, "e": 4925, "s": 4698, "text": "Assume you expected that a particular field in your CSV to have only integer values but accidentally the column has a string value. In this case you cannot process the column as integer. Let’s see how to handle such situation." }, { "code": null, "e": 5027, "s": 4925, "text": "You can choose to find the string values and replace it with any suitable value as discussed earlier." }, { "code": null, "e": 5116, "s": 5027, "text": "Once you have replaced string value you can convert the data type of column as follows —" }, { "code": null, "e": 5149, "s": 5116, "text": "df[col] = pd.to_numeric(df[col])" }, { "code": null, "e": 5421, "s": 5149, "text": "Once you have finished processing your data, the next step is to extract valuable information from the data. For the sake of discussion let us consider a very small data set comprising of marks of a couple of students. Below is the tabular representation of the CSV data." }, { "code": null, "e": 5696, "s": 5421, "text": "The basic query is to list students who scored above a certain value. The following query shows all records in which marks scored for Test1 are greater than 15. Apart from the greater than operator other relational operators can also be used such as > =, <, < =, ==, and =!." }, { "code": null, "e": 5719, "s": 5696, "text": "df.query('Test1 > 15')" }, { "code": null, "e": 5882, "s": 5719, "text": "The following query shows how to perform comparison on string values. There also exists the not equal (!=) operator. The following query retrieves marks for John." }, { "code": null, "e": 5909, "s": 5882, "text": "df.query('Name == \"John\"')" }, { "code": null, "e": 6120, "s": 5909, "text": "Apart from basic comparison for string you can also apply functions such as startswith(), endswith() and contains() to filter the data. The following example queries marks for students whose name starts with J." }, { "code": null, "e": 6174, "s": 6120, "text": "df.query('Name.str.startswith(\"J\")', engine='python')" }, { "code": null, "e": 6368, "s": 6174, "text": "Although, pandas provides ways to filter based on string valued columns but there is nothing more powerful than using regex. The following example retrieves names that begin with A using regex." }, { "code": null, "e": 6433, "s": 6368, "text": "df.query('Name.str.contains(\"^A\", regex=True)', engine='python')" }, { "code": null, "e": 6602, "s": 6433, "text": "You can also combine multiple conditions using and and or. The following query retrieves record in which students have scored more than 16 marks in the first two tests." }, { "code": null, "e": 6641, "s": 6602, "text": "df.query('Test1 > 16 and Test2 > 16)')" }, { "code": null, "e": 6952, "s": 6641, "text": "It is not always that you want to compare values with a constant. The following syntax is used to compare corresponding values of two columns and return the rows which satisfy the condition. This query shows list of students who have improved their performance in the second test as compared to the first test." }, { "code": null, "e": 6978, "s": 6952, "text": "df.query('Test1 < Test2')" }, { "code": null, "e": 7150, "s": 6978, "text": "There is a possibility in which you do not want to see results which comprise of all the columns. Let us take a look on how to conditionally retrieve marks only for Test2." }, { "code": null, "e": 7330, "s": 7150, "text": "#The following statement shows just the Name and Test2 columns only if test2 marks are more than 15. It doesn't show full rows as earlier.df[['Name', 'Test2']].query('Test2 > 15')" }, { "code": null, "e": 7473, "s": 7330, "text": "The next most common operation is to sort data. Let’s take look at an example to sort students in descending order of marks obtained in Test3." }, { "code": null, "e": 7711, "s": 7473, "text": "#Let's select only Name and Test3 columns first.temp = df[['Name', 'Test3']]#Now's let's sort by Test3 in ascending order.temp.sort_values(by=['Test3'])#Sorting by Test3 in descending order.temp.sort_values(by=['Test3'], ascending=False)" }, { "code": null, "e": 7934, "s": 7711, "text": "You can use libraries such as Matpoltlib to graph and visualise data which will help to quickly find trends and patterns in data. But for the sake of uniformity let’s use plot() function provided by Pandas dataframe class." }, { "code": null, "e": 7985, "s": 7934, "text": "A bar chart of ‘Name’ and marks scored in ‘Test1’." }, { "code": null, "e": 8018, "s": 7985, "text": "df.plot.bar(x='Name', y='Test1')" }, { "code": null, "e": 8115, "s": 8018, "text": "The following graph is a comparison between marks scored by each student in all the three tests." }, { "code": null, "e": 8168, "s": 8115, "text": "df.plot.bar(x='Name', y=['Test1', 'Test2', 'Test3'])" } ]
How to Install OpenAI Gym in a Windows Environment | by Genevieve Hayes | Towards Data Science
This is the second in a series of articles about reinforcement learning and OpenAI Gym. The first part can be found here. OpenAI Gym is an awesome tool which makes it possible for computer scientists, both amateur and professional, to experiment with a range of different reinforcement learning (RL) algorithms, and even, potentially, to develop their own. Built with the aim of becoming a standardized environment and benchmark for RL research, OpenAI Gym is a Python package comprising a selection of RL environments, ranging from simple “toy” environments, to more challenging environments, including simulated robotics environments and Atari video game environments. The only downside of the package is that, even though over 80% of the world’s desktop and laptop computers run on a Windows operating system, OpenAI Gym only supports Linux and MacOS. However, just because OpenAI Gym doesn’t support Windows, doesn’t mean that you can’t get OpenAI Gym to work on a Windows machine. In this article, I will provide the instructions for how I got OpenAI Gym up and running on my Windows 10 PC. Note: these instructions are sufficient to get OpenAI Gym’s Algorithmic, Toy Text, Classic Control, Box2D and Atari environments to work. OpenAI Gym also includes MuJoCo and Robotics environments, which allow the user to run experiments using the MuJoCo physics simulator. However, to run these environments, you will also need to install MuJoCo which will set you back at least $500 for a one year licence (unless you are a student). These instructions assume you already have Python 3.5+ installed on your computer. If you don’t already have it on your computer, install Microsoft Visual C++ Build Tools for Visual Studio 2017. This can be downloaded for free here. You will need to scroll about halfway down the page to the “Tools for Visual Studio 2017” section. Given that OpenAI Gym is not supported in a Windows environment, I thought it best to set it up in its own separate Python environment. This was to avoid potentially breaking my main Python installation. In Conda, this can be done using the following command (at the terminal or Anaconda prompt): conda create -n gym python=3 pip This command creates a Conda environment named “gym” that runs Python 3 and contains pip. If you don’t install pip at the time you create a Conda environment, then any packages you try to install within that environment will be installed globally, to your base Python environment, rather than just locally within that environment. This is because a version of pip won’t exist within your local environment. To activate your new environment type: activate gym Next run the following commands: pip install gym This does a minimum install of OpenAI Gym. conda install pystan This is necessary to run the ToyText environments. conda install gitpip install git+https://github.com/Kojoley/atari-py.git This is required to run the Atari environments. conda install swigpip install Box2D This is required to run the Box2D environments. pip install gym[all] This installs the remaining OpenAI Gym environments. Some errors may appear, but just ignore them. pip install pyglet==1.2.4pip install gym[box2d] The last two lines are necessary to avoid some bugs that can occur with Pyglet and the Box2D environments. Once you’ve done that, install any other Python packages you wish to have in your Conda environment. Install Xming on your computer, which can be downloaded for free from here. Each time you want to use OpenAI Gym, before starting your Python IDE, start Xming running by entering the following command at the Windows command prompt: set DISPLAY=:0 To test your new OpenAI Gym environment, run the following Python code: If everything has been set up correct, a window should pop up showing you the results of 1000 random actions taken in the Cart Pole environment. To test other environments, substitute the environment name for “CartPole-v0” in line 3 of the code. For example, “Taxi-v2”, “SpaceInvaders-v0” and “LunarLander-v2”. You can find the names and descriptions of all the available environments on the OpenAI Gym website here. If you followed these instructions, you should now have OpenAI Gym successfully up and running on your computer. However, now that it’s up and running, what do you do with it? In my next article, I will go through how to apply this exciting tool to reinforcement learning problems.
[ { "code": null, "e": 294, "s": 172, "text": "This is the second in a series of articles about reinforcement learning and OpenAI Gym. The first part can be found here." }, { "code": null, "e": 529, "s": 294, "text": "OpenAI Gym is an awesome tool which makes it possible for computer scientists, both amateur and professional, to experiment with a range of different reinforcement learning (RL) algorithms, and even, potentially, to develop their own." }, { "code": null, "e": 843, "s": 529, "text": "Built with the aim of becoming a standardized environment and benchmark for RL research, OpenAI Gym is a Python package comprising a selection of RL environments, ranging from simple “toy” environments, to more challenging environments, including simulated robotics environments and Atari video game environments." }, { "code": null, "e": 1027, "s": 843, "text": "The only downside of the package is that, even though over 80% of the world’s desktop and laptop computers run on a Windows operating system, OpenAI Gym only supports Linux and MacOS." }, { "code": null, "e": 1268, "s": 1027, "text": "However, just because OpenAI Gym doesn’t support Windows, doesn’t mean that you can’t get OpenAI Gym to work on a Windows machine. In this article, I will provide the instructions for how I got OpenAI Gym up and running on my Windows 10 PC." }, { "code": null, "e": 1703, "s": 1268, "text": "Note: these instructions are sufficient to get OpenAI Gym’s Algorithmic, Toy Text, Classic Control, Box2D and Atari environments to work. OpenAI Gym also includes MuJoCo and Robotics environments, which allow the user to run experiments using the MuJoCo physics simulator. However, to run these environments, you will also need to install MuJoCo which will set you back at least $500 for a one year licence (unless you are a student)." }, { "code": null, "e": 1786, "s": 1703, "text": "These instructions assume you already have Python 3.5+ installed on your computer." }, { "code": null, "e": 1936, "s": 1786, "text": "If you don’t already have it on your computer, install Microsoft Visual C++ Build Tools for Visual Studio 2017. This can be downloaded for free here." }, { "code": null, "e": 2035, "s": 1936, "text": "You will need to scroll about halfway down the page to the “Tools for Visual Studio 2017” section." }, { "code": null, "e": 2239, "s": 2035, "text": "Given that OpenAI Gym is not supported in a Windows environment, I thought it best to set it up in its own separate Python environment. This was to avoid potentially breaking my main Python installation." }, { "code": null, "e": 2332, "s": 2239, "text": "In Conda, this can be done using the following command (at the terminal or Anaconda prompt):" }, { "code": null, "e": 2365, "s": 2332, "text": "conda create -n gym python=3 pip" }, { "code": null, "e": 2455, "s": 2365, "text": "This command creates a Conda environment named “gym” that runs Python 3 and contains pip." }, { "code": null, "e": 2772, "s": 2455, "text": "If you don’t install pip at the time you create a Conda environment, then any packages you try to install within that environment will be installed globally, to your base Python environment, rather than just locally within that environment. This is because a version of pip won’t exist within your local environment." }, { "code": null, "e": 2811, "s": 2772, "text": "To activate your new environment type:" }, { "code": null, "e": 2824, "s": 2811, "text": "activate gym" }, { "code": null, "e": 2857, "s": 2824, "text": "Next run the following commands:" }, { "code": null, "e": 2873, "s": 2857, "text": "pip install gym" }, { "code": null, "e": 2916, "s": 2873, "text": "This does a minimum install of OpenAI Gym." }, { "code": null, "e": 2937, "s": 2916, "text": "conda install pystan" }, { "code": null, "e": 2988, "s": 2937, "text": "This is necessary to run the ToyText environments." }, { "code": null, "e": 3061, "s": 2988, "text": "conda install gitpip install git+https://github.com/Kojoley/atari-py.git" }, { "code": null, "e": 3109, "s": 3061, "text": "This is required to run the Atari environments." }, { "code": null, "e": 3145, "s": 3109, "text": "conda install swigpip install Box2D" }, { "code": null, "e": 3193, "s": 3145, "text": "This is required to run the Box2D environments." }, { "code": null, "e": 3214, "s": 3193, "text": "pip install gym[all]" }, { "code": null, "e": 3313, "s": 3214, "text": "This installs the remaining OpenAI Gym environments. Some errors may appear, but just ignore them." }, { "code": null, "e": 3361, "s": 3313, "text": "pip install pyglet==1.2.4pip install gym[box2d]" }, { "code": null, "e": 3468, "s": 3361, "text": "The last two lines are necessary to avoid some bugs that can occur with Pyglet and the Box2D environments." }, { "code": null, "e": 3569, "s": 3468, "text": "Once you’ve done that, install any other Python packages you wish to have in your Conda environment." }, { "code": null, "e": 3645, "s": 3569, "text": "Install Xming on your computer, which can be downloaded for free from here." }, { "code": null, "e": 3801, "s": 3645, "text": "Each time you want to use OpenAI Gym, before starting your Python IDE, start Xming running by entering the following command at the Windows command prompt:" }, { "code": null, "e": 3816, "s": 3801, "text": "set DISPLAY=:0" }, { "code": null, "e": 3888, "s": 3816, "text": "To test your new OpenAI Gym environment, run the following Python code:" }, { "code": null, "e": 4033, "s": 3888, "text": "If everything has been set up correct, a window should pop up showing you the results of 1000 random actions taken in the Cart Pole environment." }, { "code": null, "e": 4199, "s": 4033, "text": "To test other environments, substitute the environment name for “CartPole-v0” in line 3 of the code. For example, “Taxi-v2”, “SpaceInvaders-v0” and “LunarLander-v2”." }, { "code": null, "e": 4305, "s": 4199, "text": "You can find the names and descriptions of all the available environments on the OpenAI Gym website here." }, { "code": null, "e": 4481, "s": 4305, "text": "If you followed these instructions, you should now have OpenAI Gym successfully up and running on your computer. However, now that it’s up and running, what do you do with it?" } ]
Count pairs of parentheses sequences such that parentheses are balanced - GeeksforGeeks
31 May, 2021 Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair. Examples: Input: { ")())", ")", "((", "((", "(", ")", ")"} Output: 2 Bracket sequence {1, 3} and {5, 6} Input: {"()", "(())", "(())", "()"} Output: 2 Since all brackets are balanced, hence we can form 2 pairs with 4. Approach: The following steps can be followed to solve the above problem: Count required opening and closing brackets, of individuals. If required closing brackets > 0 and opening brackets is 0, then hash the bracket’s required closing number. Similarly, if required opening brackets > 0 and closing brackets is 0, then hash the bracket’s required opening number. Count the balanced bracket sequences. Add (number of balanced bracket sequences/2) to the number of pairs. For every number of sequences which requires same number of opening brackets, min(hash[open], hash[close]) will be added to the number of pairs Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count the number of pairs// of balanced parentheses#include <bits/stdc++.h>using namespace std; // Function to count the number of pairsint countPairs(string bracks[], int num){ // Hashing function to count the // opening and closing brackets unordered_map<int, int> open, close; int cnt = 0; // Traverse for all bracket sequences for (int i = 0; i < num; i++) { // Get the string string s = bracks[i]; int l = s.length(); // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for (int j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; else // Closing bracket { // If openings are there, then close it if (op) op--; else // Else increase count of closing cl++; } } // If requirements of openings // are there and no closing if (op && !cl) open[op]++; // If requirements of closing // are there and no opening if (cl && !op) close[cl]++; // Perfect if (!op && !cl) cnt++; } // Divide by two since two // perfect makes one pair cnt = cnt / 2; // Traverse in the open and find // corresponding minimum for (auto it : open) cnt += min(it.second, close[it.first]); return cnt;} // Driver Codeint main(){ string bracks[] = { ")())", ")", "((", "((", "(", ")", ")" }; int num = sizeof(bracks) / sizeof(bracks[0]); cout << countPairs(bracks, num);} // Java program to count the number of pairs// of balanced parenthesesimport java.util.HashMap; class GFG{ // Function to count the number of pairsstatic int countPairs(String[] bracks, int num){ // Hashing function to count the // opening and closing brackets HashMap<Integer, Integer> open = new HashMap<>(); HashMap<Integer, Integer> close = new HashMap<>(); int cnt = 0; // Traverse for all bracket sequences for (int i = 0; i < num; i++) { // Get the string String s = bracks[i]; int l = s.length(); // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for (int j = 0; j < l; j++) { // If it is a opening bracket if (s.charAt(j) == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) open.put(op, open.get(op) == null ? 1 : open.get(op) + 1); // If requirements of closing // are there and no opening if (cl != 0 && op == 0) close.put(cl, close.get(cl) == null ? 1 : close.get(cl) + 1); // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum for (HashMap.Entry<Integer, Integer> it : open.entrySet()) cnt += Math.min(it.getValue(), close.get(it.getKey())); return cnt;} // Driver Codepublic static void main(String[] args){ String[] bracks = { ")())", ")", "((", "((", "(", ")", ")" }; int num = bracks.length; System.out.println(countPairs(bracks, num));}} // This code is contributed by// sanjeev2552 # Python3 program to count the number of pairs# of balanced parenthesesimport math as mt # Function to count the number of pairsdef countPairs(bracks, num): # Hashing function to count the # opening and closing brackets openn=dict() close=dict() cnt = 0 # Traverse for all bracket sequences for i in range(num): # Get the string s = bracks[i] l = len(s) # Counts the opening and closing required op,cl = 0,0 # Traverse in the string for j in range(l): # If it is a opening bracket if (s[j] == '('): op+=1 else: # Closing bracket # If openings are there, then close it if (op): op-=1 else: # Else increase count of closing cl+=1 # If requirements of openings # are there and no closing if (op and cl==0): if op in openn.keys(): openn[op]+=1 else: openn[op]=1 # If requirements of closing # are there and no opening if (cl and op==0): if cl in openn.keys(): close[cl]+=1 else: close[cl]=1 # Perfect if (op==0 and cl==0): cnt+=1 # Divide by two since two # perfect makes one pair cnt = cnt //2 # Traverse in the open and find # corresponding minimum for it in openn: cnt += min(openn[it], close[it]) return cnt # Driver Codebracks= [")())", ")", "((", "((", "(", ")", ")" ]num = len(bracks) print(countPairs(bracks, num)) #This code is contributed by Mohit kumar 29 // C# program to count the number of pairs// of balanced parenthesesusing System;using System.Collections.Generic; class GFG{ // Function to count the number of pairsstatic int countPairs(string[] bracks, int num){ // Hashing function to count the // opening and closing brackets Dictionary<int, int> open = new Dictionary<int, int>(); Dictionary<int, int> close = new Dictionary<int, int>(); int cnt = 0; // Traverse for all bracket sequences for(int i = 0; i < num; i++) { // Get the string string s = bracks[i]; int l = s.Length; // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for(int j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) { if (open.ContainsKey(op)) { open[op]++; } else { open[op] = 1; } } // If requirements of closing // are there and no opening if (cl != 0 && op == 0) { if (close.ContainsKey(cl)) { close[cl]++; } else { close[cl] = 1; } } // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum foreach(KeyValuePair<int, int> it in open) { cnt += Math.Min(it.Value, close[it.Value]); } return cnt;} // Driver Codepublic static void Main(string[] args){ string[] bracks = { ")())", ")", "((", "((", "(", ")", ")" }; int num = bracks.Length; Console.Write(countPairs(bracks, num));}} // This code is contributed by rutvik_56 <script>// Javascript program to count the number of pairs// of balanced parentheses // Function to count the number of pairsfunction countPairs( bracks,num){ // Hashing function to count the // opening and closing brackets let open = new Map(); let close = new Map(); let cnt = 0; // Traverse for all bracket sequences for (let i = 0; i < num; i++) { // Get the string let s = bracks[i]; let l = s.length; // Counts the opening and closing required let op = 0, cl = 0; // Traverse in the string for (let j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) open.set(op, open.get(op) == null ? 1 : open.get(op) + 1); // If requirements of closing // are there and no opening if (cl != 0 && op == 0) close.set(cl, close.get(cl) == null ? 1 : close.get(cl) + 1); // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum for (let [key, value] of open.entries()) cnt += Math.min(value, close.get(value)); return cnt;} // Driver Codelet bracks=[")())", ")", "((", "((", "(", ")", ")"]; let num = bracks.length;document.write(countPairs(bracks, num)); // This code is contributed by patel2127</script> 2 mohit kumar 29 Akanksha_Rai sanjeev2552 AJITNAIN rutvik_56 patel2127 cpp-unordered_map Hash Parentheses-Problems Competitive Programming Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bits manipulation (Important tactics) Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm How to begin with Competitive Programming? Use of FLAG in programming Reverse a string in Java Write a program to reverse an array or string C++ Data Types Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string
[ { "code": null, "e": 25310, "s": 25282, "text": "\n31 May, 2021" }, { "code": null, "e": 25540, "s": 25310, "text": "Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair. " }, { "code": null, "e": 25551, "s": 25540, "text": "Examples: " }, { "code": null, "e": 25764, "s": 25551, "text": "Input: { \")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\"}\nOutput: 2 \nBracket sequence {1, 3} and {5, 6} \n\nInput: {\"()\", \"(())\", \"(())\", \"()\"}\nOutput: 2 \nSince all brackets are balanced, hence we can form 2 pairs with 4. " }, { "code": null, "e": 25839, "s": 25764, "text": "Approach: The following steps can be followed to solve the above problem: " }, { "code": null, "e": 25900, "s": 25839, "text": "Count required opening and closing brackets, of individuals." }, { "code": null, "e": 26009, "s": 25900, "text": "If required closing brackets > 0 and opening brackets is 0, then hash the bracket’s required closing number." }, { "code": null, "e": 26129, "s": 26009, "text": "Similarly, if required opening brackets > 0 and closing brackets is 0, then hash the bracket’s required opening number." }, { "code": null, "e": 26167, "s": 26129, "text": "Count the balanced bracket sequences." }, { "code": null, "e": 26236, "s": 26167, "text": "Add (number of balanced bracket sequences/2) to the number of pairs." }, { "code": null, "e": 26380, "s": 26236, "text": "For every number of sequences which requires same number of opening brackets, min(hash[open], hash[close]) will be added to the number of pairs" }, { "code": null, "e": 26433, "s": 26380, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26437, "s": 26433, "text": "C++" }, { "code": null, "e": 26442, "s": 26437, "text": "Java" }, { "code": null, "e": 26450, "s": 26442, "text": "Python3" }, { "code": null, "e": 26453, "s": 26450, "text": "C#" }, { "code": null, "e": 26464, "s": 26453, "text": "Javascript" }, { "code": "// C++ program to count the number of pairs// of balanced parentheses#include <bits/stdc++.h>using namespace std; // Function to count the number of pairsint countPairs(string bracks[], int num){ // Hashing function to count the // opening and closing brackets unordered_map<int, int> open, close; int cnt = 0; // Traverse for all bracket sequences for (int i = 0; i < num; i++) { // Get the string string s = bracks[i]; int l = s.length(); // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for (int j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; else // Closing bracket { // If openings are there, then close it if (op) op--; else // Else increase count of closing cl++; } } // If requirements of openings // are there and no closing if (op && !cl) open[op]++; // If requirements of closing // are there and no opening if (cl && !op) close[cl]++; // Perfect if (!op && !cl) cnt++; } // Divide by two since two // perfect makes one pair cnt = cnt / 2; // Traverse in the open and find // corresponding minimum for (auto it : open) cnt += min(it.second, close[it.first]); return cnt;} // Driver Codeint main(){ string bracks[] = { \")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\" }; int num = sizeof(bracks) / sizeof(bracks[0]); cout << countPairs(bracks, num);}", "e": 28154, "s": 26464, "text": null }, { "code": "// Java program to count the number of pairs// of balanced parenthesesimport java.util.HashMap; class GFG{ // Function to count the number of pairsstatic int countPairs(String[] bracks, int num){ // Hashing function to count the // opening and closing brackets HashMap<Integer, Integer> open = new HashMap<>(); HashMap<Integer, Integer> close = new HashMap<>(); int cnt = 0; // Traverse for all bracket sequences for (int i = 0; i < num; i++) { // Get the string String s = bracks[i]; int l = s.length(); // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for (int j = 0; j < l; j++) { // If it is a opening bracket if (s.charAt(j) == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) open.put(op, open.get(op) == null ? 1 : open.get(op) + 1); // If requirements of closing // are there and no opening if (cl != 0 && op == 0) close.put(cl, close.get(cl) == null ? 1 : close.get(cl) + 1); // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum for (HashMap.Entry<Integer, Integer> it : open.entrySet()) cnt += Math.min(it.getValue(), close.get(it.getKey())); return cnt;} // Driver Codepublic static void main(String[] args){ String[] bracks = { \")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\" }; int num = bracks.length; System.out.println(countPairs(bracks, num));}} // This code is contributed by// sanjeev2552", "e": 30295, "s": 28154, "text": null }, { "code": "# Python3 program to count the number of pairs# of balanced parenthesesimport math as mt # Function to count the number of pairsdef countPairs(bracks, num): # Hashing function to count the # opening and closing brackets openn=dict() close=dict() cnt = 0 # Traverse for all bracket sequences for i in range(num): # Get the string s = bracks[i] l = len(s) # Counts the opening and closing required op,cl = 0,0 # Traverse in the string for j in range(l): # If it is a opening bracket if (s[j] == '('): op+=1 else: # Closing bracket # If openings are there, then close it if (op): op-=1 else: # Else increase count of closing cl+=1 # If requirements of openings # are there and no closing if (op and cl==0): if op in openn.keys(): openn[op]+=1 else: openn[op]=1 # If requirements of closing # are there and no opening if (cl and op==0): if cl in openn.keys(): close[cl]+=1 else: close[cl]=1 # Perfect if (op==0 and cl==0): cnt+=1 # Divide by two since two # perfect makes one pair cnt = cnt //2 # Traverse in the open and find # corresponding minimum for it in openn: cnt += min(openn[it], close[it]) return cnt # Driver Codebracks= [\")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\" ]num = len(bracks) print(countPairs(bracks, num)) #This code is contributed by Mohit kumar 29", "e": 32043, "s": 30295, "text": null }, { "code": "// C# program to count the number of pairs// of balanced parenthesesusing System;using System.Collections.Generic; class GFG{ // Function to count the number of pairsstatic int countPairs(string[] bracks, int num){ // Hashing function to count the // opening and closing brackets Dictionary<int, int> open = new Dictionary<int, int>(); Dictionary<int, int> close = new Dictionary<int, int>(); int cnt = 0; // Traverse for all bracket sequences for(int i = 0; i < num; i++) { // Get the string string s = bracks[i]; int l = s.Length; // Counts the opening and closing required int op = 0, cl = 0; // Traverse in the string for(int j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) { if (open.ContainsKey(op)) { open[op]++; } else { open[op] = 1; } } // If requirements of closing // are there and no opening if (cl != 0 && op == 0) { if (close.ContainsKey(cl)) { close[cl]++; } else { close[cl] = 1; } } // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum foreach(KeyValuePair<int, int> it in open) { cnt += Math.Min(it.Value, close[it.Value]); } return cnt;} // Driver Codepublic static void Main(string[] args){ string[] bracks = { \")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\" }; int num = bracks.Length; Console.Write(countPairs(bracks, num));}} // This code is contributed by rutvik_56", "e": 34452, "s": 32043, "text": null }, { "code": "<script>// Javascript program to count the number of pairs// of balanced parentheses // Function to count the number of pairsfunction countPairs( bracks,num){ // Hashing function to count the // opening and closing brackets let open = new Map(); let close = new Map(); let cnt = 0; // Traverse for all bracket sequences for (let i = 0; i < num; i++) { // Get the string let s = bracks[i]; let l = s.length; // Counts the opening and closing required let op = 0, cl = 0; // Traverse in the string for (let j = 0; j < l; j++) { // If it is a opening bracket if (s[j] == '(') op++; // Closing bracket else { // If openings are there, then close it if (op != 0) op--; // Else increase count of closing else cl++; } } // If requirements of openings // are there and no closing if (op != 0 && cl == 0) open.set(op, open.get(op) == null ? 1 : open.get(op) + 1); // If requirements of closing // are there and no opening if (cl != 0 && op == 0) close.set(cl, close.get(cl) == null ? 1 : close.get(cl) + 1); // Perfect if (op == 0 && cl == 0) cnt++; } // Divide by two since two // perfect makes one pair cnt /= 2; // Traverse in the open and find // corresponding minimum for (let [key, value] of open.entries()) cnt += Math.min(value, close.get(value)); return cnt;} // Driver Codelet bracks=[\")())\", \")\", \"((\", \"((\", \"(\", \")\", \")\"]; let num = bracks.length;document.write(countPairs(bracks, num)); // This code is contributed by patel2127</script>", "e": 36410, "s": 34452, "text": null }, { "code": null, "e": 36412, "s": 36410, "text": "2" }, { "code": null, "e": 36429, "s": 36414, "text": "mohit kumar 29" }, { "code": null, "e": 36442, "s": 36429, "text": "Akanksha_Rai" }, { "code": null, "e": 36454, "s": 36442, "text": "sanjeev2552" }, { "code": null, "e": 36463, "s": 36454, "text": "AJITNAIN" }, { "code": null, "e": 36473, "s": 36463, "text": "rutvik_56" }, { "code": null, "e": 36483, "s": 36473, "text": "patel2127" }, { "code": null, "e": 36501, "s": 36483, "text": "cpp-unordered_map" }, { "code": null, "e": 36506, "s": 36501, "text": "Hash" }, { "code": null, "e": 36527, "s": 36506, "text": "Parentheses-Problems" }, { "code": null, "e": 36551, "s": 36527, "text": "Competitive Programming" }, { "code": null, "e": 36559, "s": 36551, "text": "Strings" }, { "code": null, "e": 36564, "s": 36559, "text": "Hash" }, { "code": null, "e": 36572, "s": 36564, "text": "Strings" }, { "code": null, "e": 36670, "s": 36572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36679, "s": 36670, "text": "Comments" }, { "code": null, "e": 36692, "s": 36679, "text": "Old Comments" }, { "code": null, "e": 36730, "s": 36692, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 36755, "s": 36730, "text": "Formatted output in Java" }, { "code": null, "e": 36803, "s": 36755, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 36846, "s": 36803, "text": "How to begin with Competitive Programming?" }, { "code": null, "e": 36873, "s": 36846, "text": "Use of FLAG in programming" }, { "code": null, "e": 36898, "s": 36873, "text": "Reverse a string in Java" }, { "code": null, "e": 36944, "s": 36898, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36959, "s": 36944, "text": "C++ Data Types" }, { "code": null, "e": 36993, "s": 36959, "text": "Longest Common Subsequence | DP-4" } ]
Java Examples - Delete a directory
How to delete a directory? Following example demonstares how to delete a directory after deleting its files and directories by the use ofdir.isDirectory(),dir.list() and deleteDir() methods of File class. import java.io.File; public class Main { public static void main(String[] argv) throws Exception { deleteDir(new File("c:\\temp")); } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir (new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); System.out.println("The directory is deleted."); } } The above code sample will produce the following result. The directory is deleted. Print Add Notes Bookmark this page
[ { "code": null, "e": 2095, "s": 2068, "text": "How to delete a directory?" }, { "code": null, "e": 2273, "s": 2095, "text": "Following example demonstares how to delete a directory after deleting its files and directories by the use ofdir.isDirectory(),dir.list() and deleteDir() methods of File class." }, { "code": null, "e": 2854, "s": 2273, "text": "import java.io.File;\n\npublic class Main {\n public static void main(String[] argv) throws Exception {\n deleteDir(new File(\"c:\\\\temp\"));\n }\n public static boolean deleteDir(File dir) {\n if (dir.isDirectory()) {\n String[] children = dir.list();\n for (int i = 0; i < children.length; i++) {\n boolean success = deleteDir (new File(dir, children[i]));\n \n if (!success) {\n return false;\n }\n }\n }\n return dir.delete();\n System.out.println(\"The directory is deleted.\");\n }\n}" }, { "code": null, "e": 2911, "s": 2854, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2938, "s": 2911, "text": "The directory is deleted.\n" }, { "code": null, "e": 2945, "s": 2938, "text": " Print" }, { "code": null, "e": 2956, "s": 2945, "text": " Add Notes" } ]
Arrays.deepToString() in Java with Example - GeeksforGeeks
28 Jun, 2021 java.util.Arrays.deepToString(Object[]) method is a java.util.Arrays class method. Returns a string representation of the “deep contents” of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings. The simple toString() method works well for simple arrays, but doesn’t work for multidimensional arrays. This method is designed for converting multi-dimensional arrays to strings. Syntax: public static String deepToString(Object[] arr) arr - An array whose string representation is needed This function returns string representation of arr[]. It returns "null" if the specified array is null. Example: Let us suppose that we are making a 2-D array of 3 rows and 3 column. 2 3 4 5 6 7 2 4 9 If use deepToString() method to print the 2-D array, we will get string representation as :- [[2,3,4], [5,6,7], [2,4,9]] Printing multidimensional Array // A Java program to print 2D array using deepToString()import java.util.Arrays; public class GfG{ public static void main(String[] args) { // Create a 2D array int[][] mat = new int[2][2]; mat[0][0] = 99; mat[0][1] = 151; mat[1][0] = 30; mat[1][1] = 5; // print 2D integer array using deepToString() System.out.println(Arrays.deepToString(mat)); }} Output: [[99, 151], [30, 5]] toString() vs deepToString()toString() works well for single dimensional arrays, but doesn’t work for multidimensional arrays. // Java program to demonstrate that toString works if we // want to print single dimensional array, but doesn't work// for multidimensional array.import java.util.Arrays;public class Deeptostring{ public static void main(String[] args) { // Trying to print array of strings using toString String[] strs = new String[] {"practice.geeksforgeeks.org", "quiz.geeksforgeeks.org" }; System.out.println(Arrays.toString(strs)); // Trying to print multidimensional array using // toString int[][] mat = new int[2][2]; mat[0][0] = 99; mat[0][1] = 151; mat[1][0] = 30; mat[1][1] = 50; System.out.println(Arrays.toString(mat)); }} Output: [practice.geeksforgeeks.org, quiz.geeksforgeeks.org] [[I@15db9742, [I@6d06d69c] Note : We can use a loop to print contents of a multidimensional array using deepToString(). deepToString() works for both single and multidimensional, but doesn’t work single dimensional array of primitives // Java program to demonstrate that deepToString(strs))// works for single dimensional arrays also, but doesn't// work single dimensional array of primitive types.import java.util.Arrays;public class Deeptostring{ public static void main(String[] args) { String[] strs = new String[] {"practice.geeksforgeeks.org", "quiz.geeksforgeeks.org" }; System.out.println(Arrays.deepToString(strs)); Integer [] arr1 = {10, 20, 30, 40}; System.out.println(Arrays.deepToString(arr1)); /* Uncommenting below code would cause error as deepToString() doesn't work for primitive types int [] arr2 = {10, 20, 30, 40}; System.out.println(Arrays.deepToString(arr2)); */ }} Output: [practice.geeksforgeeks.org, quiz.geeksforgeeks.org] [10, 20, 30, 40] Reference:https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[]) This article is contributed by Mohit Gupta. 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.. Java - util package Java-Arrays Java-Collections Java Java Java-Collections 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 Functional Interfaces in Java Comparator Interface in Java with Examples Commonly Asked Java Programming Interview Questions | Set 2 HashMap get() Method in Java Strings in Java
[ { "code": null, "e": 23972, "s": 23944, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24055, "s": 23972, "text": "java.util.Arrays.deepToString(Object[]) method is a java.util.Arrays class method." }, { "code": null, "e": 24499, "s": 24055, "text": "Returns a string representation of the “deep contents” of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings. The simple toString() method works well for simple arrays, but doesn’t work for multidimensional arrays. This method is designed for converting multi-dimensional arrays to strings." }, { "code": null, "e": 24507, "s": 24499, "text": "Syntax:" }, { "code": null, "e": 24716, "s": 24507, "text": "public static String deepToString(Object[] arr)\n\narr - An array whose string representation is needed\n\nThis function returns string representation of arr[].\nIt returns \"null\" if the specified array is null." }, { "code": null, "e": 24725, "s": 24716, "text": "Example:" }, { "code": null, "e": 24964, "s": 24725, "text": "Let us suppose that we are making a 2-D array of\n3 rows and 3 column.\n 2 3 4 \n 5 6 7\n 2 4 9\n\nIf use deepToString() method to print the 2-D array, \nwe will get string representation as :-\n[[2,3,4], [5,6,7], [2,4,9]]\n" }, { "code": null, "e": 24996, "s": 24964, "text": "Printing multidimensional Array" }, { "code": "// A Java program to print 2D array using deepToString()import java.util.Arrays; public class GfG{ public static void main(String[] args) { // Create a 2D array int[][] mat = new int[2][2]; mat[0][0] = 99; mat[0][1] = 151; mat[1][0] = 30; mat[1][1] = 5; // print 2D integer array using deepToString() System.out.println(Arrays.deepToString(mat)); }}", "e": 25414, "s": 24996, "text": null }, { "code": null, "e": 25422, "s": 25414, "text": "Output:" }, { "code": null, "e": 25443, "s": 25422, "text": "[[99, 151], [30, 5]]" }, { "code": null, "e": 25570, "s": 25443, "text": "toString() vs deepToString()toString() works well for single dimensional arrays, but doesn’t work for multidimensional arrays." }, { "code": "// Java program to demonstrate that toString works if we // want to print single dimensional array, but doesn't work// for multidimensional array.import java.util.Arrays;public class Deeptostring{ public static void main(String[] args) { // Trying to print array of strings using toString String[] strs = new String[] {\"practice.geeksforgeeks.org\", \"quiz.geeksforgeeks.org\" }; System.out.println(Arrays.toString(strs)); // Trying to print multidimensional array using // toString int[][] mat = new int[2][2]; mat[0][0] = 99; mat[0][1] = 151; mat[1][0] = 30; mat[1][1] = 50; System.out.println(Arrays.toString(mat)); }}", "e": 26350, "s": 25570, "text": null }, { "code": null, "e": 26358, "s": 26350, "text": "Output:" }, { "code": null, "e": 26439, "s": 26358, "text": "[practice.geeksforgeeks.org, quiz.geeksforgeeks.org]\n[[I@15db9742, [I@6d06d69c]\n" }, { "code": null, "e": 26532, "s": 26439, "text": "Note : We can use a loop to print contents of a multidimensional array using deepToString()." }, { "code": null, "e": 26647, "s": 26532, "text": "deepToString() works for both single and multidimensional, but doesn’t work single dimensional array of primitives" }, { "code": "// Java program to demonstrate that deepToString(strs))// works for single dimensional arrays also, but doesn't// work single dimensional array of primitive types.import java.util.Arrays;public class Deeptostring{ public static void main(String[] args) { String[] strs = new String[] {\"practice.geeksforgeeks.org\", \"quiz.geeksforgeeks.org\" }; System.out.println(Arrays.deepToString(strs)); Integer [] arr1 = {10, 20, 30, 40}; System.out.println(Arrays.deepToString(arr1)); /* Uncommenting below code would cause error as deepToString() doesn't work for primitive types int [] arr2 = {10, 20, 30, 40}; System.out.println(Arrays.deepToString(arr2)); */ }}", "e": 27471, "s": 26647, "text": null }, { "code": null, "e": 27479, "s": 27471, "text": "Output:" }, { "code": null, "e": 27550, "s": 27479, "text": "[practice.geeksforgeeks.org, quiz.geeksforgeeks.org]\n[10, 20, 30, 40]\n" }, { "code": null, "e": 27657, "s": 27550, "text": "Reference:https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])" }, { "code": null, "e": 27953, "s": 27657, "text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.." }, { "code": null, "e": 27973, "s": 27953, "text": "Java - util package" }, { "code": null, "e": 27985, "s": 27973, "text": "Java-Arrays" }, { "code": null, "e": 28002, "s": 27985, "text": "Java-Collections" }, { "code": null, "e": 28007, "s": 28002, "text": "Java" }, { "code": null, "e": 28012, "s": 28007, "text": "Java" }, { "code": null, "e": 28029, "s": 28012, "text": "Java-Collections" }, { "code": null, "e": 28127, "s": 28029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28136, "s": 28127, "text": "Comments" }, { "code": null, "e": 28149, "s": 28136, "text": "Old Comments" }, { "code": null, "e": 28195, "s": 28149, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28210, "s": 28195, "text": "Stream In Java" }, { "code": null, "e": 28231, "s": 28210, "text": "Constructors in Java" }, { "code": null, "e": 28248, "s": 28231, "text": "Generics in Java" }, { "code": null, "e": 28267, "s": 28248, "text": "Exceptions in Java" }, { "code": null, "e": 28297, "s": 28267, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28340, "s": 28297, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28400, "s": 28340, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 28429, "s": 28400, "text": "HashMap get() Method in Java" } ]
Web Scraping Using Selenium — Python | by Atindra Bandi | Towards Data Science
Before we delve into the topic of this article let us first understand what is web-scraping and how is it useful. What is web-scraping? What is web-scraping? Web scraping is a technique for extracting information from the internet automatically using a software that simulates human web surfing. 2. How is web-scraping useful? Web scraping helps us extract large volumes of data about customers, products, people, stock markets, etc. It is usually difficult to get this kind of information on a large scale using traditional data collection methods. We can utilize the data collected from a website such as e-commerce portal, social media channels to understand customer behaviors and sentiments, buying patterns, and brand attribute associations which are critical insights for any business. Let’s now get our hands dirty!! Since we have defined our purpose of scraping, let us delve into the nitty-gritty of how to actually do all the fun stuff! Before that below are some of the housekeeping instructions regarding installations of packages. a. Python version: We will be using Python 3.0, however feel free to use Python 2.0 by making slight adjustments. We will be using jupyter notebook, so you don’t need any command line knowledge. b. Selenium package: You can install selenium package using the following command !pip install selenium c. Chrome driver: Please install the latest version of chromedriver from here. Please note you need Google Chrome installed on your machines to work through this illustration. The first and foremost thing while scraping a website is to understand the structure of the website. We will be scraping Edmunds.com, a car forum. This website aids people in their car buying decisions. People can post their reviews about different cars in the discussion forums (very similar to how one posts reviews on Amazon). We will be scraping the discussion about entry level luxury car brands. We will scrape ~5000 comments from different users across multiple pages. We will scrape user id, date of comment and comments and export it into a csv file for any further analysis. Let’s begin writing our scraper! We will first import important packages in our Notebook — #Importing packagesfrom selenium import webdriverimport pandas as pd Let’s now create a new instance of google chrome. This will help our program open an url in google chrome. driver = webdriver.Chrome('Path in your computer where you have installed chromedriver') Let’s now access google chrome and open our website. By the way, chrome knows that you are accessing it through an automated software! driver.get('https://forums.edmunds.com/discussion/2864/general/x/entry-level-luxury-performance-sedans/p702') So, how does our web page look like? We will inspect 3 items (user id, date and comment) on our web page and understand how we can extract them. User id: Inspecting the userid, we can see the highlighted text represents the XML code for user id. User id: Inspecting the userid, we can see the highlighted text represents the XML code for user id. The XML path (XPath)for the userid is shown below. There is an interesting thing to note here that the XML path contains a comment id, which uniquely denotes each comment on the website. This will be very helpful as we try to recursively scrape multiple comments . //*[@id=”Comment_5561090"]/div/div[2]/div[1]/span[1]/a[2] If we see the XPath in the picture, we will observe that it contains the user id ‘dino001’. How do we extract the values inside a XPath? Selenium has a function called “find_elements_by_xpath”. We will pass our XPath into this function and get a selenium element. Once we have the element, we can extract the text inside our XPath using the ‘text’ function. In our case the text is basically the user id (‘dino001’). userid_element = driver.find_elements_by_xpath('//*[@id="Comment_5561090"]/div/div[2]/div[1]/span[1]/a[2]')[0]userid = userid_element.text 2. Comment Date: Similar to the user id, we will now inspect the date when the comment was posted. Let’s also see the XPath for the comment date. Again note the unique comment id in the XPath. //*[@id="Comment_5561090"]/div/div[2]/div[2]/span[1]/a/time So, how do we extract date from the above XPath? We will again use the function “find_elements_by_xpath” to get the selenium element. Now, if we carefully observe the highlighted text in the picture, we will see that the date is stored inside the ‘title’ attribute. We can access the values inside attributes using the function ‘get_attribute’. We will pass the tag name in this function to get the value inside the same. user_date = driver.find_elements_by_xpath('//*[@id="Comment_5561090"]/div/div[2]/div[2]/span[1]/a/time')[0]date = user_date.get_attribute('title') 3. Comments: Lastly, let’s explore how to extract the comments of each user. Below is the XPath for the user comment — //*[@id="Comment_5561090"]/div/div[3]/div/div[1] Once again, we have the comment id in our XPath. Similar to the userid we will extract the comment from the above XPath user_message = driver.find_elements_by_xpath('//*[@id="Comment_5561090"]/div/div[3]/div/div[1]')[0]comment = user_message.text We just learnt how to scrape different elements from a web page. Now how to recursively extract these items for 5000 users? As discussed above, we will use the comment ids, which are unique for a comment to extract different users data. If we see the XPath for the entire comment block, we will see that it has a comment id associated with it. //*[@id="Comment_5561090"] The following code snippet will help us extract all the comment ids on a particular web page. We will again use the function ‘find_elements_by_xpath’ on the above XPath and extract the ids from the ‘id’ attribute. ids = driver.find_elements_by_xpath("//*[contains(@id,'Comment_')]") comment_ids = []for i in ids: comment_ids.append(i.get_attribute('id')) The above code gives us a list of all the comment ids from a particular web page. How to bring all this together? Now we will bring all the things we have seen so far into one big code, which will recursively help us extract 5000 comments. We can extract user ids, date and comments for each user on a particular web page by looping through all the comment ids we found in the previous code. Below is the code snippet to extract all comments from a particular web page. Lastly, if you check our url has page numbers, starting from 702. So, we can recursively go to previous pages by simply changing the page numbers in the url to extract more comments until we get the desired number of comments. This process will take some time depending on the computational power of your computer. So, chill, have a coffee, talk to your friends and family and let Selenium do its job! Summary: We learnt how to scrape a website using Selenium in Python and get large amounts of data. You can carry out multiple unstructured data analytics and find interesting trends, sentiments, etc. using this data. If anyone is interested in looking at the complete code, here is the link to my Github. Let me know if this was helpful. Enjoy Scraping BUT BE CAREFUL! If you liked reading this, I would recommend reading another article about scraping Reddit data using Reddit API and Google BigQuery written by a fellow classmate (Akhilesh Narapareddy) at the University of Texas, Austin.
[ { "code": null, "e": 285, "s": 171, "text": "Before we delve into the topic of this article let us first understand what is web-scraping and how is it useful." }, { "code": null, "e": 307, "s": 285, "text": "What is web-scraping?" }, { "code": null, "e": 329, "s": 307, "text": "What is web-scraping?" }, { "code": null, "e": 467, "s": 329, "text": "Web scraping is a technique for extracting information from the internet automatically using a software that simulates human web surfing." }, { "code": null, "e": 498, "s": 467, "text": "2. How is web-scraping useful?" }, { "code": null, "e": 964, "s": 498, "text": "Web scraping helps us extract large volumes of data about customers, products, people, stock markets, etc. It is usually difficult to get this kind of information on a large scale using traditional data collection methods. We can utilize the data collected from a website such as e-commerce portal, social media channels to understand customer behaviors and sentiments, buying patterns, and brand attribute associations which are critical insights for any business." }, { "code": null, "e": 996, "s": 964, "text": "Let’s now get our hands dirty!!" }, { "code": null, "e": 1216, "s": 996, "text": "Since we have defined our purpose of scraping, let us delve into the nitty-gritty of how to actually do all the fun stuff! Before that below are some of the housekeeping instructions regarding installations of packages." }, { "code": null, "e": 1411, "s": 1216, "text": "a. Python version: We will be using Python 3.0, however feel free to use Python 2.0 by making slight adjustments. We will be using jupyter notebook, so you don’t need any command line knowledge." }, { "code": null, "e": 1493, "s": 1411, "text": "b. Selenium package: You can install selenium package using the following command" }, { "code": null, "e": 1515, "s": 1493, "text": "!pip install selenium" }, { "code": null, "e": 1594, "s": 1515, "text": "c. Chrome driver: Please install the latest version of chromedriver from here." }, { "code": null, "e": 1691, "s": 1594, "text": "Please note you need Google Chrome installed on your machines to work through this illustration." }, { "code": null, "e": 2093, "s": 1691, "text": "The first and foremost thing while scraping a website is to understand the structure of the website. We will be scraping Edmunds.com, a car forum. This website aids people in their car buying decisions. People can post their reviews about different cars in the discussion forums (very similar to how one posts reviews on Amazon). We will be scraping the discussion about entry level luxury car brands." }, { "code": null, "e": 2276, "s": 2093, "text": "We will scrape ~5000 comments from different users across multiple pages. We will scrape user id, date of comment and comments and export it into a csv file for any further analysis." }, { "code": null, "e": 2309, "s": 2276, "text": "Let’s begin writing our scraper!" }, { "code": null, "e": 2367, "s": 2309, "text": "We will first import important packages in our Notebook —" }, { "code": null, "e": 2436, "s": 2367, "text": "#Importing packagesfrom selenium import webdriverimport pandas as pd" }, { "code": null, "e": 2543, "s": 2436, "text": "Let’s now create a new instance of google chrome. This will help our program open an url in google chrome." }, { "code": null, "e": 2632, "s": 2543, "text": "driver = webdriver.Chrome('Path in your computer where you have installed chromedriver')" }, { "code": null, "e": 2767, "s": 2632, "text": "Let’s now access google chrome and open our website. By the way, chrome knows that you are accessing it through an automated software!" }, { "code": null, "e": 2877, "s": 2767, "text": "driver.get('https://forums.edmunds.com/discussion/2864/general/x/entry-level-luxury-performance-sedans/p702')" }, { "code": null, "e": 2914, "s": 2877, "text": "So, how does our web page look like?" }, { "code": null, "e": 3022, "s": 2914, "text": "We will inspect 3 items (user id, date and comment) on our web page and understand how we can extract them." }, { "code": null, "e": 3123, "s": 3022, "text": "User id: Inspecting the userid, we can see the highlighted text represents the XML code for user id." }, { "code": null, "e": 3224, "s": 3123, "text": "User id: Inspecting the userid, we can see the highlighted text represents the XML code for user id." }, { "code": null, "e": 3489, "s": 3224, "text": "The XML path (XPath)for the userid is shown below. There is an interesting thing to note here that the XML path contains a comment id, which uniquely denotes each comment on the website. This will be very helpful as we try to recursively scrape multiple comments ." }, { "code": null, "e": 3547, "s": 3489, "text": "//*[@id=”Comment_5561090\"]/div/div[2]/div[1]/span[1]/a[2]" }, { "code": null, "e": 3639, "s": 3547, "text": "If we see the XPath in the picture, we will observe that it contains the user id ‘dino001’." }, { "code": null, "e": 3684, "s": 3639, "text": "How do we extract the values inside a XPath?" }, { "code": null, "e": 3964, "s": 3684, "text": "Selenium has a function called “find_elements_by_xpath”. We will pass our XPath into this function and get a selenium element. Once we have the element, we can extract the text inside our XPath using the ‘text’ function. In our case the text is basically the user id (‘dino001’)." }, { "code": null, "e": 4103, "s": 3964, "text": "userid_element = driver.find_elements_by_xpath('//*[@id=\"Comment_5561090\"]/div/div[2]/div[1]/span[1]/a[2]')[0]userid = userid_element.text" }, { "code": null, "e": 4202, "s": 4103, "text": "2. Comment Date: Similar to the user id, we will now inspect the date when the comment was posted." }, { "code": null, "e": 4296, "s": 4202, "text": "Let’s also see the XPath for the comment date. Again note the unique comment id in the XPath." }, { "code": null, "e": 4356, "s": 4296, "text": "//*[@id=\"Comment_5561090\"]/div/div[2]/div[2]/span[1]/a/time" }, { "code": null, "e": 4405, "s": 4356, "text": "So, how do we extract date from the above XPath?" }, { "code": null, "e": 4778, "s": 4405, "text": "We will again use the function “find_elements_by_xpath” to get the selenium element. Now, if we carefully observe the highlighted text in the picture, we will see that the date is stored inside the ‘title’ attribute. We can access the values inside attributes using the function ‘get_attribute’. We will pass the tag name in this function to get the value inside the same." }, { "code": null, "e": 4925, "s": 4778, "text": "user_date = driver.find_elements_by_xpath('//*[@id=\"Comment_5561090\"]/div/div[2]/div[2]/span[1]/a/time')[0]date = user_date.get_attribute('title')" }, { "code": null, "e": 5002, "s": 4925, "text": "3. Comments: Lastly, let’s explore how to extract the comments of each user." }, { "code": null, "e": 5044, "s": 5002, "text": "Below is the XPath for the user comment —" }, { "code": null, "e": 5093, "s": 5044, "text": "//*[@id=\"Comment_5561090\"]/div/div[3]/div/div[1]" }, { "code": null, "e": 5213, "s": 5093, "text": "Once again, we have the comment id in our XPath. Similar to the userid we will extract the comment from the above XPath" }, { "code": null, "e": 5340, "s": 5213, "text": "user_message = driver.find_elements_by_xpath('//*[@id=\"Comment_5561090\"]/div/div[3]/div/div[1]')[0]comment = user_message.text" }, { "code": null, "e": 5464, "s": 5340, "text": "We just learnt how to scrape different elements from a web page. Now how to recursively extract these items for 5000 users?" }, { "code": null, "e": 5684, "s": 5464, "text": "As discussed above, we will use the comment ids, which are unique for a comment to extract different users data. If we see the XPath for the entire comment block, we will see that it has a comment id associated with it." }, { "code": null, "e": 5711, "s": 5684, "text": "//*[@id=\"Comment_5561090\"]" }, { "code": null, "e": 5925, "s": 5711, "text": "The following code snippet will help us extract all the comment ids on a particular web page. We will again use the function ‘find_elements_by_xpath’ on the above XPath and extract the ids from the ‘id’ attribute." }, { "code": null, "e": 6076, "s": 5925, "text": "ids = driver.find_elements_by_xpath(\"//*[contains(@id,'Comment_')]\") comment_ids = []for i in ids: comment_ids.append(i.get_attribute('id'))" }, { "code": null, "e": 6158, "s": 6076, "text": "The above code gives us a list of all the comment ids from a particular web page." }, { "code": null, "e": 6190, "s": 6158, "text": "How to bring all this together?" }, { "code": null, "e": 6468, "s": 6190, "text": "Now we will bring all the things we have seen so far into one big code, which will recursively help us extract 5000 comments. We can extract user ids, date and comments for each user on a particular web page by looping through all the comment ids we found in the previous code." }, { "code": null, "e": 6546, "s": 6468, "text": "Below is the code snippet to extract all comments from a particular web page." }, { "code": null, "e": 6773, "s": 6546, "text": "Lastly, if you check our url has page numbers, starting from 702. So, we can recursively go to previous pages by simply changing the page numbers in the url to extract more comments until we get the desired number of comments." }, { "code": null, "e": 6948, "s": 6773, "text": "This process will take some time depending on the computational power of your computer. So, chill, have a coffee, talk to your friends and family and let Selenium do its job!" }, { "code": null, "e": 7253, "s": 6948, "text": "Summary: We learnt how to scrape a website using Selenium in Python and get large amounts of data. You can carry out multiple unstructured data analytics and find interesting trends, sentiments, etc. using this data. If anyone is interested in looking at the complete code, here is the link to my Github." }, { "code": null, "e": 7317, "s": 7253, "text": "Let me know if this was helpful. Enjoy Scraping BUT BE CAREFUL!" } ]
JavaTuples - Triplet Class
The org.javatuples.Triplet class represents a Tuple with three elements. Following is the declaration for org.javatuples.Triplet class − public final class Triplet<A,B,C> extends Tuple implements IValue0<A>, IValue1<B>, IValue2<C> Triplet(A value0, B value1, C value2) This creates a Triplet Tuple. Similarly setAt1() upto setAt2() set the value at index 1 and so on. Quartet add(Unit tuple) This method returns a Quartet tuple. Similarly other methods to add tuples are available e.g. add(Pair tuple) returns Quintet and upto add(Septet tuple) returns Decade tuple. Quartet add(X0 value) This method add a value to the tuple and returns a Quartet tuple. Similarly other methods to add values are available e.g. add(X0 value0, X1 value1) returns Quintet and so on upto add() with seven parameters. Quartet addAt0(Unit value) This method add a Unit tuple at index 0 and returns a Quartet tuple. Similarly other methods to add tuples are available e.g. addAt0(Pair value) returns Quintet and so on upto addAt0(Septet). Other similar method are addAt1(Unit value) which add a unit at index0 and have similar methods upto addAt2(Septet). Quartet addAt0(X0 value) This method add a value at index 0 and returns a Quartet tuple. Similarly other methods to add values are available e.g. addAt0(X0 value0, X1 value1) returns Quintet and so on upto addAt0() with seven parameters. Other similar method are addAt1(X0 value) which add a value at index0 and have similar methods upto addAt2() with seven parameters. static <X> Triplet<X,X,X> fromArray(X[] array) Create tuple from array. static <X> Triplet<X,X,X> fromCollection(Collection<X> collection) Create tuple from collection. static <X> Triplet<X,X,X> fromIterable(Iterable<X> iterable) Create tuple from iterable. static <X> Triplet<X,X,X> fromIterable(Iterable<X> iterable, int index) Create tuple from iterable, starting from the specified index. int getSize() Return the size of the tuple. A getValue0() Returns the value of the tuple at index 0. Similarly getValue1() upto getValue2() returns the value at index 1 and so on. Pair<B,C> removeFrom0() Return the tuple after removing value of the tuple at index 0. Similarly removeFrom1() upto removeFrom2() returns the tuple after removing value of the tuple at index 1 and so on. <X> Triplet<X,B,C> setAt0(X value) Set the value of the tuple at index 0. static <A> Triplet<A,B,C> with(A value0, B value1, C value2) Create the tuple using given value. This class inherits methods from the following classes − org.javatuples.Tuple org.javatuples.Tuple Object Object Let's see Triplet Class in action. Here we'll see how to use various methods. Create a java class file named TupleTester in C:\>JavaTuples. File: TupleTester.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import org.javatuples.Pair; import org.javatuples.Quartet; import org.javatuples.Triplet; public class TupleTester { public static void main(String args[]){ Triplet<Integer, Integer, Integer> triplet = Triplet.with(5, 6, 7); System.out.println(triplet); boolean isPresent = triplet.contains(5); System.out.println("5 is present: " + isPresent); List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Quartet<Integer, Integer, Integer, String> quartet = triplet.add("Test"); System.out.println(quartet); Integer value = triplet.getValue0(); System.out.println(value); Pair<Integer, Integer> pair = triplet.removeFrom0(); System.out.println(pair); Triplet<Integer, Integer, Integer> triplet1 = Triplet.fromCollection(list); System.out.println(triplet1); } } Verify the result Compile the classes using javac compiler as follows − C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java Now run the TupleTester to see the result − C:\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester Verify the Output [5, 6, 7] 5 is present: true [5, 6, 7, Test] 5 [6, 7] [1, 2, 3] Print Add Notes Bookmark this page
[ { "code": null, "e": 2612, "s": 2539, "text": "The org.javatuples.Triplet class represents a Tuple with three elements." }, { "code": null, "e": 2676, "s": 2612, "text": "Following is the declaration for org.javatuples.Triplet class −" }, { "code": null, "e": 2780, "s": 2676, "text": "public final class Triplet<A,B,C>\n extends Tuple\n implements IValue0<A>, IValue1<B>, IValue2<C>\n" }, { "code": null, "e": 2818, "s": 2780, "text": "Triplet(A value0, B value1, C value2)" }, { "code": null, "e": 2848, "s": 2818, "text": "This creates a Triplet Tuple." }, { "code": null, "e": 2917, "s": 2848, "text": "Similarly setAt1() upto setAt2() set the value at index 1 and so on." }, { "code": null, "e": 2941, "s": 2917, "text": "Quartet add(Unit tuple)" }, { "code": null, "e": 2978, "s": 2941, "text": "This method returns a Quartet tuple." }, { "code": null, "e": 3116, "s": 2978, "text": "Similarly other methods to add tuples are available e.g. add(Pair tuple) returns Quintet and upto add(Septet tuple) returns Decade tuple." }, { "code": null, "e": 3138, "s": 3116, "text": "Quartet add(X0 value)" }, { "code": null, "e": 3205, "s": 3138, "text": "This method add a value to the tuple and returns a Quartet tuple. " }, { "code": null, "e": 3348, "s": 3205, "text": "Similarly other methods to add values are available e.g. add(X0 value0, X1 value1) returns Quintet and so on upto add() with seven parameters." }, { "code": null, "e": 3375, "s": 3348, "text": "Quartet addAt0(Unit value)" }, { "code": null, "e": 3444, "s": 3375, "text": "This method add a Unit tuple at index 0 and returns a Quartet tuple." }, { "code": null, "e": 3684, "s": 3444, "text": "Similarly other methods to add tuples are available e.g. addAt0(Pair value) returns Quintet and so on upto addAt0(Septet). Other similar method are addAt1(Unit value) which add a unit at index0 and have similar methods upto addAt2(Septet)." }, { "code": null, "e": 3709, "s": 3684, "text": "Quartet addAt0(X0 value)" }, { "code": null, "e": 3773, "s": 3709, "text": "This method add a value at index 0 and returns a Quartet tuple." }, { "code": null, "e": 4054, "s": 3773, "text": "Similarly other methods to add values are available e.g. addAt0(X0 value0, X1 value1) returns Quintet and so on upto addAt0() with seven parameters. Other similar method are addAt1(X0 value) which add a value at index0 and have similar methods upto addAt2() with seven parameters." }, { "code": null, "e": 4101, "s": 4054, "text": "static <X> Triplet<X,X,X> fromArray(X[] array)" }, { "code": null, "e": 4126, "s": 4101, "text": "Create tuple from array." }, { "code": null, "e": 4193, "s": 4126, "text": "static <X> Triplet<X,X,X> fromCollection(Collection<X> collection)" }, { "code": null, "e": 4223, "s": 4193, "text": "Create tuple from collection." }, { "code": null, "e": 4284, "s": 4223, "text": "static <X> Triplet<X,X,X> fromIterable(Iterable<X> iterable)" }, { "code": null, "e": 4312, "s": 4284, "text": "Create tuple from iterable." }, { "code": null, "e": 4384, "s": 4312, "text": "static <X> Triplet<X,X,X> fromIterable(Iterable<X> iterable, int index)" }, { "code": null, "e": 4447, "s": 4384, "text": "Create tuple from iterable, starting from the specified index." }, { "code": null, "e": 4461, "s": 4447, "text": "int getSize()" }, { "code": null, "e": 4491, "s": 4461, "text": "Return the size of the tuple." }, { "code": null, "e": 4505, "s": 4491, "text": "A getValue0()" }, { "code": null, "e": 4548, "s": 4505, "text": "Returns the value of the tuple at index 0." }, { "code": null, "e": 4627, "s": 4548, "text": "Similarly getValue1() upto getValue2() returns the value at index 1 and so on." }, { "code": null, "e": 4651, "s": 4627, "text": "Pair<B,C> removeFrom0()" }, { "code": null, "e": 4714, "s": 4651, "text": "Return the tuple after removing value of the tuple at index 0." }, { "code": null, "e": 4831, "s": 4714, "text": "Similarly removeFrom1() upto removeFrom2() returns the tuple after removing value of the tuple at index 1 and so on." }, { "code": null, "e": 4866, "s": 4831, "text": "<X> Triplet<X,B,C> setAt0(X value)" }, { "code": null, "e": 4905, "s": 4866, "text": "Set the value of the tuple at index 0." }, { "code": null, "e": 4966, "s": 4905, "text": "static <A> Triplet<A,B,C> with(A value0, B value1, C value2)" }, { "code": null, "e": 5002, "s": 4966, "text": "Create the tuple using given value." }, { "code": null, "e": 5059, "s": 5002, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 5080, "s": 5059, "text": "org.javatuples.Tuple" }, { "code": null, "e": 5101, "s": 5080, "text": "org.javatuples.Tuple" }, { "code": null, "e": 5108, "s": 5101, "text": "Object" }, { "code": null, "e": 5115, "s": 5108, "text": "Object" }, { "code": null, "e": 5193, "s": 5115, "text": "Let's see Triplet Class in action. Here we'll see how to use various methods." }, { "code": null, "e": 5255, "s": 5193, "text": "Create a java class file named TupleTester in C:\\>JavaTuples." }, { "code": null, "e": 5278, "s": 5255, "text": "File: TupleTester.java" }, { "code": null, "e": 6253, "s": 5278, "text": "package com.tutorialspoint;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.javatuples.Pair;\nimport org.javatuples.Quartet;\nimport org.javatuples.Triplet;\n\npublic class TupleTester {\n public static void main(String args[]){\n Triplet<Integer, Integer, Integer> triplet = Triplet.with(5, 6, 7);\n System.out.println(triplet);\n boolean isPresent = triplet.contains(5);\n System.out.println(\"5 is present: \" + isPresent);\n List<Integer> list = new ArrayList<>();\n list.add(1);\n list.add(2);\n list.add(3);\n Quartet<Integer, Integer, Integer, String> quartet = triplet.add(\"Test\");\n System.out.println(quartet);\n Integer value = triplet.getValue0();\n System.out.println(value);\n Pair<Integer, Integer> pair = triplet.removeFrom0();\n System.out.println(pair);\n Triplet<Integer, Integer, Integer> triplet1 = \n Triplet.fromCollection(list); \n System.out.println(triplet1);\n }\n}" }, { "code": null, "e": 6271, "s": 6253, "text": "Verify the result" }, { "code": null, "e": 6325, "s": 6271, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 6407, "s": 6325, "text": "C:\\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java\n" }, { "code": null, "e": 6451, "s": 6407, "text": "Now run the TupleTester to see the result −" }, { "code": null, "e": 6528, "s": 6451, "text": "C:\\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester\n" }, { "code": null, "e": 6546, "s": 6528, "text": "Verify the Output" }, { "code": null, "e": 6611, "s": 6546, "text": "[5, 6, 7]\n5 is present: true\n[5, 6, 7, Test]\n5\n[6, 7]\n[1, 2, 3]\n" }, { "code": null, "e": 6618, "s": 6611, "text": " Print" }, { "code": null, "e": 6629, "s": 6618, "text": " Add Notes" } ]
A simple 2D CNN for MNIST digit recognition | by Sambit Mahapatra | Towards Data Science
Convolutional Neural Networks (CNNs) are the current state-of-art architecture for image classification task. Whether it is facial recognition, self driving cars or object detection, CNNs are being used everywhere. In this post, a simple 2-D Convolutional Neural Network (CNN) model is designed using keras with tensorflow backend for the well known MNIST digit recognition task. The whole work flow can be: Preparing the dataBuilding and compiling of the modelTraining and evaluating the modelSaving the model to disk for reuse Preparing the data Building and compiling of the model Training and evaluating the model Saving the model to disk for reuse github.com Preparing the data The data set used here is MNIST dataset as mentioned above. The MNIST database (Modified National Institute of Standards and Technology database) is a large database of handwritten digits (0 to 9). The database contains 60,000 training images and 10,000 testing images each of size 28x28. The first step is to load the dataset, which can be easily done through the keras api. import kerasfrom keras.datasets import mnist#load mnist dataset(X_train, y_train), (X_test, y_test) = mnist.load_data() #everytime loading data won't be so easy :) Here X_train contains 60,000 training images’ data each of size 28x28 and y_train contains their corresponding labels. Similarly, X_test contains 10,000 testing images’ data each of dimension 28x28 and y_test contains their corresponding labels. Let’s visualize few data from training to get a better idea about the purpose of the deep learning model. import matplotlib.pyplot as pltfig = plt.figure()for i in range(9): plt.subplot(3,3,i+1) plt.tight_layout() plt.imshow(X_train[i], cmap='gray', interpolation='none') plt.title("Digit: {}".format(y_train[i])) plt.xticks([]) plt.yticks([])fig As can be seen here, at left top corner the image of ‘5’ is stored is X_train[0] and y_train[0] contains label ‘5’. Our deep learning model should be able to only take the handwritten image and predict the actual digit written. Now, to prepare the data we need some processing on the images like resizing images, normalizing the pixel values etc. #reshaping#this assumes our data format#For 3D data, "channels_last" assumes (conv_dim1, conv_dim2, conv_dim3, channels) while #"channels_first" assumes (channels, conv_dim1, conv_dim2, conv_dim3).if k.image_data_format() == 'channels_first': X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)#more reshapingX_train = X_train.astype('float32')X_test = X_test.astype('float32')X_train /= 255X_test /= 255print('X_train shape:', X_train.shape) #X_train shape: (60000, 28, 28, 1) After doing the necessary processing on the image informations, the label data i.e. y_train and y_test need to be converted into categorical formats like label ‘3’ should be converted to a vector [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] for model building. import keras#set number of categoriesnum_category = 10# convert class vectors to binary class matricesy_train = keras.utils.to_categorical(y_train, num_category)y_test = keras.utils.to_categorical(y_test, num_category) Building and compiling of the model After the data is ready to be fed to the model, we need to define the architecture of the model and compile it with necessary optimizer function, loss function and performance metrics. The architecture followed here is 2 convolution layers followed by pooling layer, a fully connected layer and softmax layer respectively. Multiple filters are used at each convolution layer, for different types of feature extraction. One intuitive explanation can be if first filter helps in detecting the straight lines in the image, second filter will help in detecting circles and so on. Explanations for technical execution of each layer will be a part of upcoming post. For better understanding of each layer, may refer to http://cs231n.github.io/convolutional-networks/ After both maxpooling and fully connected layer, dropout is introduced as regularization in our model to reduce over-fitting problem. ##model buildingmodel = Sequential()#convolutional layer with rectified linear unit activationmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))#32 convolution filters used each of size 3x3#againmodel.add(Conv2D(64, (3, 3), activation='relu'))#64 convolution filters used each of size 3x3#choose the best features via poolingmodel.add(MaxPooling2D(pool_size=(2, 2)))#randomly turn neurons on and off to improve convergencemodel.add(Dropout(0.25))#flatten since too many dimensions, we only want a classification outputmodel.add(Flatten())#fully connected to get all relevant datamodel.add(Dense(128, activation='relu'))#one more dropout for convergence' sake :) model.add(Dropout(0.5))#output a softmax to squash the matrix into output probabilitiesmodel.add(Dense(num_category, activation='softmax')) After the architecture of the model is defined, the model needs to be compiled. Here, we are using categorical_crossentropy loss function as it is a multi-class classification problem. Since all the labels carry similar weight we prefer accuracy as performance metric. A popular gradient descent technique called AdaDelta is used for optimization of the model parameters. #Adaptive learning rate (adaDelta) is a popular form of gradient descent rivaled only by adam and adagrad#categorical ce since we have multiple classes (10) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) Training and evaluating the model After the model architecture is defined and compiled, the model needs to be trained with training data to be able to recognize the handwritten digits. Hence we will fit the model with X_train and y_train. batch_size = 128num_epoch = 10#model trainingmodel_log = model.fit(X_train, y_train, batch_size=batch_size, epochs=num_epoch, verbose=1, validation_data=(X_test, y_test)) Here, one epoch means one forward and one backward pass of all the training samples. Batch size implies number of training samples in one forward/backward pass. The training output is: Now the trained model needs to be evaluated in terms of performance. score = model.evaluate(X_test, y_test, verbose=0)print('Test loss:', score[0]) #Test loss: 0.0296396646054print('Test accuracy:', score[1]) #Test accuracy: 0.9904 Test accuracy 99%+ implies the model is trained well for prediction. If we visualize the whole training log, then with more number of epochs the loss and accuracy of the model on training and testing data converged thus making the model a stable one. import os# plotting the metricsfig = plt.figure()plt.subplot(2,1,1)plt.plot(model_log.history['acc'])plt.plot(model_log.history['val_acc'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='lower right')plt.subplot(2,1,2)plt.plot(model_log.history['loss'])plt.plot(model_log.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper right')plt.tight_layout()fig Saving the model to disk for reuse Now, the trained model needs to be serialized. The architecture or structure of the model will be stored in a json file and the weights will be stored in hdf5 file format. #Save the model# serialize model to JSONmodel_digit_json = model.to_json()with open("model_digit.json", "w") as json_file: json_file.write(model_digit_json)# serialize weights to HDF5model.save_weights("model_digit.h5")print("Saved model to disk") Hence the saved model can be reused later or easily ported to other environments too. In the upcoming posts, we will see how to deploy this trained model at production. Enjoy deep learning!
[ { "code": null, "e": 580, "s": 172, "text": "Convolutional Neural Networks (CNNs) are the current state-of-art architecture for image classification task. Whether it is facial recognition, self driving cars or object detection, CNNs are being used everywhere. In this post, a simple 2-D Convolutional Neural Network (CNN) model is designed using keras with tensorflow backend for the well known MNIST digit recognition task. The whole work flow can be:" }, { "code": null, "e": 701, "s": 580, "text": "Preparing the dataBuilding and compiling of the modelTraining and evaluating the modelSaving the model to disk for reuse" }, { "code": null, "e": 720, "s": 701, "text": "Preparing the data" }, { "code": null, "e": 756, "s": 720, "text": "Building and compiling of the model" }, { "code": null, "e": 790, "s": 756, "text": "Training and evaluating the model" }, { "code": null, "e": 825, "s": 790, "text": "Saving the model to disk for reuse" }, { "code": null, "e": 836, "s": 825, "text": "github.com" }, { "code": null, "e": 855, "s": 836, "text": "Preparing the data" }, { "code": null, "e": 1231, "s": 855, "text": "The data set used here is MNIST dataset as mentioned above. The MNIST database (Modified National Institute of Standards and Technology database) is a large database of handwritten digits (0 to 9). The database contains 60,000 training images and 10,000 testing images each of size 28x28. The first step is to load the dataset, which can be easily done through the keras api." }, { "code": null, "e": 1395, "s": 1231, "text": "import kerasfrom keras.datasets import mnist#load mnist dataset(X_train, y_train), (X_test, y_test) = mnist.load_data() #everytime loading data won't be so easy :)" }, { "code": null, "e": 1747, "s": 1395, "text": "Here X_train contains 60,000 training images’ data each of size 28x28 and y_train contains their corresponding labels. Similarly, X_test contains 10,000 testing images’ data each of dimension 28x28 and y_test contains their corresponding labels. Let’s visualize few data from training to get a better idea about the purpose of the deep learning model." }, { "code": null, "e": 1994, "s": 1747, "text": "import matplotlib.pyplot as pltfig = plt.figure()for i in range(9): plt.subplot(3,3,i+1) plt.tight_layout() plt.imshow(X_train[i], cmap='gray', interpolation='none') plt.title(\"Digit: {}\".format(y_train[i])) plt.xticks([]) plt.yticks([])fig" }, { "code": null, "e": 2222, "s": 1994, "text": "As can be seen here, at left top corner the image of ‘5’ is stored is X_train[0] and y_train[0] contains label ‘5’. Our deep learning model should be able to only take the handwritten image and predict the actual digit written." }, { "code": null, "e": 2341, "s": 2222, "text": "Now, to prepare the data we need some processing on the images like resizing images, normalizing the pixel values etc." }, { "code": null, "e": 3128, "s": 2341, "text": "#reshaping#this assumes our data format#For 3D data, \"channels_last\" assumes (conv_dim1, conv_dim2, conv_dim3, channels) while #\"channels_first\" assumes (channels, conv_dim1, conv_dim2, conv_dim3).if k.image_data_format() == 'channels_first': X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)#more reshapingX_train = X_train.astype('float32')X_test = X_test.astype('float32')X_train /= 255X_test /= 255print('X_train shape:', X_train.shape) #X_train shape: (60000, 28, 28, 1)" }, { "code": null, "e": 3375, "s": 3128, "text": "After doing the necessary processing on the image informations, the label data i.e. y_train and y_test need to be converted into categorical formats like label ‘3’ should be converted to a vector [0, 0, 0, 1, 0, 0, 0, 0, 0, 0] for model building." }, { "code": null, "e": 3594, "s": 3375, "text": "import keras#set number of categoriesnum_category = 10# convert class vectors to binary class matricesy_train = keras.utils.to_categorical(y_train, num_category)y_test = keras.utils.to_categorical(y_test, num_category)" }, { "code": null, "e": 3630, "s": 3594, "text": "Building and compiling of the model" }, { "code": null, "e": 3815, "s": 3630, "text": "After the data is ready to be fed to the model, we need to define the architecture of the model and compile it with necessary optimizer function, loss function and performance metrics." }, { "code": null, "e": 4391, "s": 3815, "text": "The architecture followed here is 2 convolution layers followed by pooling layer, a fully connected layer and softmax layer respectively. Multiple filters are used at each convolution layer, for different types of feature extraction. One intuitive explanation can be if first filter helps in detecting the straight lines in the image, second filter will help in detecting circles and so on. Explanations for technical execution of each layer will be a part of upcoming post. For better understanding of each layer, may refer to http://cs231n.github.io/convolutional-networks/" }, { "code": null, "e": 4525, "s": 4391, "text": "After both maxpooling and fully connected layer, dropout is introduced as regularization in our model to reduce over-fitting problem." }, { "code": null, "e": 5394, "s": 4525, "text": "##model buildingmodel = Sequential()#convolutional layer with rectified linear unit activationmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))#32 convolution filters used each of size 3x3#againmodel.add(Conv2D(64, (3, 3), activation='relu'))#64 convolution filters used each of size 3x3#choose the best features via poolingmodel.add(MaxPooling2D(pool_size=(2, 2)))#randomly turn neurons on and off to improve convergencemodel.add(Dropout(0.25))#flatten since too many dimensions, we only want a classification outputmodel.add(Flatten())#fully connected to get all relevant datamodel.add(Dense(128, activation='relu'))#one more dropout for convergence' sake :) model.add(Dropout(0.5))#output a softmax to squash the matrix into output probabilitiesmodel.add(Dense(num_category, activation='softmax'))" }, { "code": null, "e": 5766, "s": 5394, "text": "After the architecture of the model is defined, the model needs to be compiled. Here, we are using categorical_crossentropy loss function as it is a multi-class classification problem. Since all the labels carry similar weight we prefer accuracy as performance metric. A popular gradient descent technique called AdaDelta is used for optimization of the model parameters." }, { "code": null, "e": 6068, "s": 5766, "text": "#Adaptive learning rate (adaDelta) is a popular form of gradient descent rivaled only by adam and adagrad#categorical ce since we have multiple classes (10) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])" }, { "code": null, "e": 6102, "s": 6068, "text": "Training and evaluating the model" }, { "code": null, "e": 6307, "s": 6102, "text": "After the model architecture is defined and compiled, the model needs to be trained with training data to be able to recognize the handwritten digits. Hence we will fit the model with X_train and y_train." }, { "code": null, "e": 6514, "s": 6307, "text": "batch_size = 128num_epoch = 10#model trainingmodel_log = model.fit(X_train, y_train, batch_size=batch_size, epochs=num_epoch, verbose=1, validation_data=(X_test, y_test))" }, { "code": null, "e": 6699, "s": 6514, "text": "Here, one epoch means one forward and one backward pass of all the training samples. Batch size implies number of training samples in one forward/backward pass. The training output is:" }, { "code": null, "e": 6768, "s": 6699, "text": "Now the trained model needs to be evaluated in terms of performance." }, { "code": null, "e": 6931, "s": 6768, "text": "score = model.evaluate(X_test, y_test, verbose=0)print('Test loss:', score[0]) #Test loss: 0.0296396646054print('Test accuracy:', score[1]) #Test accuracy: 0.9904" }, { "code": null, "e": 7182, "s": 6931, "text": "Test accuracy 99%+ implies the model is trained well for prediction. If we visualize the whole training log, then with more number of epochs the loss and accuracy of the model on training and testing data converged thus making the model a stable one." }, { "code": null, "e": 7659, "s": 7182, "text": "import os# plotting the metricsfig = plt.figure()plt.subplot(2,1,1)plt.plot(model_log.history['acc'])plt.plot(model_log.history['val_acc'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='lower right')plt.subplot(2,1,2)plt.plot(model_log.history['loss'])plt.plot(model_log.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper right')plt.tight_layout()fig" }, { "code": null, "e": 7694, "s": 7659, "text": "Saving the model to disk for reuse" }, { "code": null, "e": 7866, "s": 7694, "text": "Now, the trained model needs to be serialized. The architecture or structure of the model will be stored in a json file and the weights will be stored in hdf5 file format." }, { "code": null, "e": 8117, "s": 7866, "text": "#Save the model# serialize model to JSONmodel_digit_json = model.to_json()with open(\"model_digit.json\", \"w\") as json_file: json_file.write(model_digit_json)# serialize weights to HDF5model.save_weights(\"model_digit.h5\")print(\"Saved model to disk\")" }, { "code": null, "e": 8286, "s": 8117, "text": "Hence the saved model can be reused later or easily ported to other environments too. In the upcoming posts, we will see how to deploy this trained model at production." } ]
Find MongoDB records based on a condition?
To find MongoDB based on a condition, use find() and set the condition. Let us create a collection with documents − > db.demo708.insertOne({"Name":"John",Marks:54}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702e4d346dcb074dc6f33") } > db.demo708.insertOne({"Name":"Chris",Marks:35}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702e6d346dcb074dc6f34") } > db.demo708.insertOne({"Name":"David",Marks:45}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702ebd346dcb074dc6f35") } > db.demo708.insertOne({"Name":"Bob",Marks:40}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702fad346dcb074dc6f36") } Display all documents from a collection with the help of find() method − > db.demo708.find(); This will produce the following output − { "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 } { "_id" : ObjectId("5ea702e6d346dcb074dc6f34"), "Name" : "Chris", "Marks" : 35 } { "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 } { "_id" : ObjectId("5ea702fad346dcb074dc6f36"), "Name" : "Bob", "Marks" : 40 } Following is the query to find MongoDB records based on a condition − > db.demo708.find({Marks:{$gt:40}}); This will produce the following output − { "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 } { "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }
[ { "code": null, "e": 1178, "s": 1062, "text": "To find MongoDB based on a condition, use find() and set the condition. Let us create a collection with documents −" }, { "code": null, "e": 1719, "s": 1178, "text": "> db.demo708.insertOne({\"Name\":\"John\",Marks:54});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea702e4d346dcb074dc6f33\")\n}\n> db.demo708.insertOne({\"Name\":\"Chris\",Marks:35});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea702e6d346dcb074dc6f34\")\n}\n> db.demo708.insertOne({\"Name\":\"David\",Marks:45});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea702ebd346dcb074dc6f35\")\n}\n> db.demo708.insertOne({\"Name\":\"Bob\",Marks:40});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea702fad346dcb074dc6f36\")\n}" }, { "code": null, "e": 1792, "s": 1719, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1813, "s": 1792, "text": "> db.demo708.find();" }, { "code": null, "e": 1854, "s": 1813, "text": "This will produce the following output −" }, { "code": null, "e": 2175, "s": 1854, "text": "{ \"_id\" : ObjectId(\"5ea702e4d346dcb074dc6f33\"), \"Name\" : \"John\", \"Marks\" : 54 }\n{ \"_id\" : ObjectId(\"5ea702e6d346dcb074dc6f34\"), \"Name\" : \"Chris\", \"Marks\" : 35 }\n{ \"_id\" : ObjectId(\"5ea702ebd346dcb074dc6f35\"), \"Name\" : \"David\", \"Marks\" : 45 }\n{ \"_id\" : ObjectId(\"5ea702fad346dcb074dc6f36\"), \"Name\" : \"Bob\", \"Marks\" : 40 }" }, { "code": null, "e": 2245, "s": 2175, "text": "Following is the query to find MongoDB records based on a condition −" }, { "code": null, "e": 2282, "s": 2245, "text": "> db.demo708.find({Marks:{$gt:40}});" }, { "code": null, "e": 2323, "s": 2282, "text": "This will produce the following output −" }, { "code": null, "e": 2484, "s": 2323, "text": "{ \"_id\" : ObjectId(\"5ea702e4d346dcb074dc6f33\"), \"Name\" : \"John\", \"Marks\" : 54 }\n{ \"_id\" : ObjectId(\"5ea702ebd346dcb074dc6f35\"), \"Name\" : \"David\", \"Marks\" : 45 }" } ]
Find any one of the multiple repeating elements in read only array - GeeksforGeeks
22 Jun, 2021 Given a read only array of size ( n+1 ), find one of the multiple repeating elements in the array where the array contains integers only between 1 and n. Read only array means that the contents of the array can’t be modified.Examples: Input : n = 5 arr[] = {1, 1, 2, 3, 5, 4} Output : One of the numbers repeated in the array is: 1 Input : n = 10 arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4} Output : One of the numbers repeated in the array is: 4 OR 5 Since, the size of the array is n+1 and elements ranges from 1 to n then it is confirmed that there will be at least one repeating element.A simple solution is to create a count array and store counts of all elements. As soon as we encounter an element with count more than 1, we return it. This solution works in O(n) time and requires O(n) extra space.A space optimized solution is to break the given range (from 1 to n) into blocks of size equal to sqrt(n). We maintain the count of elements belonging to each block for every block. Now as the size of array is (n+1) and blocks are of size sqrt(n), then there will be one such block whose size will be more than sqrt(n). For the block whose count is greater than sqrt(n), we can use hashing for the elements of this block to find which element appears more than once. Explanation: The method described above works because of the following two reasons: There would always be a block which has count greater than sqrt(n) because of one extra element. Even when one extra element has been added it will occupy a position in one of the blocks only, making that block to be selected.The selected block definitely has a repeating element. Consider that ith block is selected. Size of the block is greater than sqrt(n) (Hence, it is selected) Maximum distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ]. There would always be a block which has count greater than sqrt(n) because of one extra element. Even when one extra element has been added it will occupy a position in one of the blocks only, making that block to be selected. The selected block definitely has a repeating element. Consider that ith block is selected. Size of the block is greater than sqrt(n) (Hence, it is selected) Maximum distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ]. Note: The last block formed may or may not have range equal to sqrt(n). Thus, checking if this block has a repeating element will be different than other blocks. However, this difficulty can be overcome from implementation point of view by initialising the selected block with the last block. This is safe because at least one block has to get selected.Below is the step by step algorithm to solve this problem: Divide the array in blocks of size sqrt(n).Make a count array which stores the count of element for each block.Pick up the block which has count more than sqrt(n), setting the last block as default.For the elements belonging to the selected block, use the method of hashing(explained in next step) to find the repeating element in that block.We can create a hash array of key value pair, where key is the element in the block and value is the count of number of times the given key is appearing. This can be easily implemented using unordered_map in C++ STL. Divide the array in blocks of size sqrt(n). Make a count array which stores the count of element for each block. Pick up the block which has count more than sqrt(n), setting the last block as default. For the elements belonging to the selected block, use the method of hashing(explained in next step) to find the repeating element in that block. We can create a hash array of key value pair, where key is the element in the block and value is the count of number of times the given key is appearing. This can be easily implemented using unordered_map in C++ STL. Below is the implementation of above idea: C++ Java Python3 C# Javascript // C++ program to find one of the repeating// elements in a read only array#include <bits/stdc++.h>using namespace std; // Function to find one of the repeating// elementsint findRepeatingNumber(const int arr[], int n){ // Size of blocks except the // last block is sq int sq = sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int count[range] = {0}; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block unordered_map<int, int> m; for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m[arr[i]]++; // repeating element found if (m[arr[i]] > 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver Programint main(){ // read only array, not to be modified const int arr[] = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; cout << "One of the numbers repeated in" " the array is: " << findRepeatingNumber(arr, n) << endl;} // Java program to find one of the repeating// elements in a read only arrayimport java.io.*;import java.util.*; class GFG{ // Function to find one of the repeating // elements static int findRepeatingNumber(int[] arr, int n) { // Size of blocks except the // last block is sq int sq = (int) Math.sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int[] count = new int[range]; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block HashMap<Integer, Integer> m = new HashMap<>(); for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m.put(arr[i], 1); // repeating element found if (m.get(arr[i]) == 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver codepublic static void main(String args[]){ // read only array, not to be modified int[] arr = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; System.out.println("One of the numbers repeated in the array is: " + findRepeatingNumber(arr, n));}} // This code is contributed by rachana soma # Python 3program to find one of the repeating# elements in a read only arrayfrom math import sqrt # Function to find one of the repeating# elementsdef findRepeatingNumber(arr, n): # Size of blocks except the # last block is sq sq = sqrt(n) # Number of blocks to incorporate 1 to # n values blocks are numbered from 0 # to range-1 (both included) range__= int((n / sq) + 1) # Count array maintains the count for # all blocks count = [0 for i in range(range__)] # Traversing the read only array and # updating count for i in range(0, n + 1, 1): # arr[i] belongs to block number # (arr[i]-1)/sq i is considered # to start from 0 count[int((arr[i] - 1) / sq)] += 1 # The selected_block is set to last # block by default. Rest of the blocks # are checked selected_block = range__ - 1 for i in range(0, range__ - 1, 1): if (count[i] > sq): selected_block = i break # after finding block with size > sq # method of hashing is used to find # the element repeating in this block m = {i:0 for i in range(n)} for i in range(0, n + 1, 1): # checks if the element belongs # to the selected_block if (((selected_block * sq) < arr[i]) and (arr[i] <= ((selected_block + 1) * sq))): m[arr[i]] += 1 # repeating element found if (m[arr[i]] > 1): return arr[i] # return -1 if no repeating element exists return -1 # Driver Codeif __name__ == '__main__': # read only array, not to be modified arr = [1, 1, 2, 3, 5, 4] # array of size 6(n + 1) having # elements between 1 and 5 n = 5 print("One of the numbers repeated in the array is:", findRepeatingNumber(arr, n)) # This code is contributed by# Sahil_shelangia // C# program to find one of the repeating// elements in a read only arrayusing System;using System.Collections.Generic; class GFG{ // Function to find one of the repeating // elements static int findRepeatingNumber(int[] arr, int n) { // Size of blocks except the // last block is sq int sq = (int) Math.Sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int[] count = new int[range]; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m.Add(arr[i], 1); // repeating element found if (m[arr[i]] == 1) return arr[i]; } } // return -1 if no repeating element exists return -1; } // Driver codepublic static void Main(String []args){ // read only array, not to be modified int[] arr = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; Console.WriteLine("One of the numbers repeated in the array is: " + findRepeatingNumber(arr, n));}} // This code contributed by Rajput-Ji <script> // JavaScript program to find one of the repeating// elements in a read only array // Function to find one of the repeating// elementsfunction findRepeatingNumber(arr, n) { // Size of blocks except the // last block is sq let sq = Math.sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) let range = Math.floor(n / sq) + 1; // Count array maintains the count for // all blocks let count = new Array(range).fill(0); // Traversing the read only array and // updating count for (let i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[Math.floor((arr[i] - 1) / sq)]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked let selected_block = range - 1; for (let i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block let m = new Map(); for (let i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if (((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m[arr[i]]++; if (m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1) } else { m.set(arr[i], 1) } // repeating element found if (m.get(arr[i]) > 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver Program // read only array, not to be modifiedconst arr = [1, 1, 2, 3, 5, 4]; // array of size 6(n + 1) having// elements between 1 and 5let n = 5; document.write("One of the numbers repeated in" + " the array is: " + findRepeatingNumber(arr, n) + "<br>"); </script> Output: One of the numbers repeated in the array is: 1 Time Complexity: O(N) Auxiliary Space: sqrt(N)This article is contributed by Aanya Jindal. 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. sahilshelangia rachana soma Rajput-Ji _saurabh_jaiswal cpp-unordered_map Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 25981, "s": 25953, "text": "\n22 Jun, 2021" }, { "code": null, "e": 26218, "s": 25981, "text": "Given a read only array of size ( n+1 ), find one of the multiple repeating elements in the array where the array contains integers only between 1 and n. Read only array means that the contents of the array can’t be modified.Examples: " }, { "code": null, "e": 26451, "s": 26218, "text": "Input : n = 5\n arr[] = {1, 1, 2, 3, 5, 4}\nOutput : One of the numbers repeated in the array is: 1\n\nInput : n = 10\n arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4}\nOutput : One of the numbers repeated in the array is: 4 OR 5" }, { "code": null, "e": 27360, "s": 26453, "text": "Since, the size of the array is n+1 and elements ranges from 1 to n then it is confirmed that there will be at least one repeating element.A simple solution is to create a count array and store counts of all elements. As soon as we encounter an element with count more than 1, we return it. This solution works in O(n) time and requires O(n) extra space.A space optimized solution is to break the given range (from 1 to n) into blocks of size equal to sqrt(n). We maintain the count of elements belonging to each block for every block. Now as the size of array is (n+1) and blocks are of size sqrt(n), then there will be one such block whose size will be more than sqrt(n). For the block whose count is greater than sqrt(n), we can use hashing for the elements of this block to find which element appears more than once. Explanation: The method described above works because of the following two reasons: " }, { "code": null, "e": 27910, "s": 27360, "text": "There would always be a block which has count greater than sqrt(n) because of one extra element. Even when one extra element has been added it will occupy a position in one of the blocks only, making that block to be selected.The selected block definitely has a repeating element. Consider that ith block is selected. Size of the block is greater than sqrt(n) (Hence, it is selected) Maximum distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ]." }, { "code": null, "e": 28137, "s": 27910, "text": "There would always be a block which has count greater than sqrt(n) because of one extra element. Even when one extra element has been added it will occupy a position in one of the blocks only, making that block to be selected." }, { "code": null, "e": 28461, "s": 28137, "text": "The selected block definitely has a repeating element. Consider that ith block is selected. Size of the block is greater than sqrt(n) (Hence, it is selected) Maximum distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ]." }, { "code": null, "e": 28875, "s": 28461, "text": "Note: The last block formed may or may not have range equal to sqrt(n). Thus, checking if this block has a repeating element will be different than other blocks. However, this difficulty can be overcome from implementation point of view by initialising the selected block with the last block. This is safe because at least one block has to get selected.Below is the step by step algorithm to solve this problem: " }, { "code": null, "e": 29434, "s": 28875, "text": "Divide the array in blocks of size sqrt(n).Make a count array which stores the count of element for each block.Pick up the block which has count more than sqrt(n), setting the last block as default.For the elements belonging to the selected block, use the method of hashing(explained in next step) to find the repeating element in that block.We can create a hash array of key value pair, where key is the element in the block and value is the count of number of times the given key is appearing. This can be easily implemented using unordered_map in C++ STL." }, { "code": null, "e": 29478, "s": 29434, "text": "Divide the array in blocks of size sqrt(n)." }, { "code": null, "e": 29547, "s": 29478, "text": "Make a count array which stores the count of element for each block." }, { "code": null, "e": 29635, "s": 29547, "text": "Pick up the block which has count more than sqrt(n), setting the last block as default." }, { "code": null, "e": 29780, "s": 29635, "text": "For the elements belonging to the selected block, use the method of hashing(explained in next step) to find the repeating element in that block." }, { "code": null, "e": 29997, "s": 29780, "text": "We can create a hash array of key value pair, where key is the element in the block and value is the count of number of times the given key is appearing. This can be easily implemented using unordered_map in C++ STL." }, { "code": null, "e": 30042, "s": 29997, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 30046, "s": 30042, "text": "C++" }, { "code": null, "e": 30051, "s": 30046, "text": "Java" }, { "code": null, "e": 30059, "s": 30051, "text": "Python3" }, { "code": null, "e": 30062, "s": 30059, "text": "C#" }, { "code": null, "e": 30073, "s": 30062, "text": "Javascript" }, { "code": "// C++ program to find one of the repeating// elements in a read only array#include <bits/stdc++.h>using namespace std; // Function to find one of the repeating// elementsint findRepeatingNumber(const int arr[], int n){ // Size of blocks except the // last block is sq int sq = sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int count[range] = {0}; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block unordered_map<int, int> m; for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m[arr[i]]++; // repeating element found if (m[arr[i]] > 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver Programint main(){ // read only array, not to be modified const int arr[] = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; cout << \"One of the numbers repeated in\" \" the array is: \" << findRepeatingNumber(arr, n) << endl;}", "e": 32022, "s": 30073, "text": null }, { "code": "// Java program to find one of the repeating// elements in a read only arrayimport java.io.*;import java.util.*; class GFG{ // Function to find one of the repeating // elements static int findRepeatingNumber(int[] arr, int n) { // Size of blocks except the // last block is sq int sq = (int) Math.sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int[] count = new int[range]; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block HashMap<Integer, Integer> m = new HashMap<>(); for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m.put(arr[i], 1); // repeating element found if (m.get(arr[i]) == 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver codepublic static void main(String args[]){ // read only array, not to be modified int[] arr = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; System.out.println(\"One of the numbers repeated in the array is: \" + findRepeatingNumber(arr, n));}} // This code is contributed by rachana soma", "e": 34322, "s": 32022, "text": null }, { "code": "# Python 3program to find one of the repeating# elements in a read only arrayfrom math import sqrt # Function to find one of the repeating# elementsdef findRepeatingNumber(arr, n): # Size of blocks except the # last block is sq sq = sqrt(n) # Number of blocks to incorporate 1 to # n values blocks are numbered from 0 # to range-1 (both included) range__= int((n / sq) + 1) # Count array maintains the count for # all blocks count = [0 for i in range(range__)] # Traversing the read only array and # updating count for i in range(0, n + 1, 1): # arr[i] belongs to block number # (arr[i]-1)/sq i is considered # to start from 0 count[int((arr[i] - 1) / sq)] += 1 # The selected_block is set to last # block by default. Rest of the blocks # are checked selected_block = range__ - 1 for i in range(0, range__ - 1, 1): if (count[i] > sq): selected_block = i break # after finding block with size > sq # method of hashing is used to find # the element repeating in this block m = {i:0 for i in range(n)} for i in range(0, n + 1, 1): # checks if the element belongs # to the selected_block if (((selected_block * sq) < arr[i]) and (arr[i] <= ((selected_block + 1) * sq))): m[arr[i]] += 1 # repeating element found if (m[arr[i]] > 1): return arr[i] # return -1 if no repeating element exists return -1 # Driver Codeif __name__ == '__main__': # read only array, not to be modified arr = [1, 1, 2, 3, 5, 4] # array of size 6(n + 1) having # elements between 1 and 5 n = 5 print(\"One of the numbers repeated in the array is:\", findRepeatingNumber(arr, n)) # This code is contributed by# Sahil_shelangia", "e": 36223, "s": 34322, "text": null }, { "code": "// C# program to find one of the repeating// elements in a read only arrayusing System;using System.Collections.Generic; class GFG{ // Function to find one of the repeating // elements static int findRepeatingNumber(int[] arr, int n) { // Size of blocks except the // last block is sq int sq = (int) Math.Sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) int range = (n / sq) + 1; // Count array maintains the count for // all blocks int[] count = new int[range]; // Traversing the read only array and // updating count for (int i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[(arr[i] - 1) / sq]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked int selected_block = range - 1; for (int i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block Dictionary<int,int> m = new Dictionary<int,int>(); for (int i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if ( ((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m.Add(arr[i], 1); // repeating element found if (m[arr[i]] == 1) return arr[i]; } } // return -1 if no repeating element exists return -1; } // Driver codepublic static void Main(String []args){ // read only array, not to be modified int[] arr = { 1, 1, 2, 3, 5, 4 }; // array of size 6(n + 1) having // elements between 1 and 5 int n = 5; Console.WriteLine(\"One of the numbers repeated in the array is: \" + findRepeatingNumber(arr, n));}} // This code contributed by Rajput-Ji", "e": 38528, "s": 36223, "text": null }, { "code": "<script> // JavaScript program to find one of the repeating// elements in a read only array // Function to find one of the repeating// elementsfunction findRepeatingNumber(arr, n) { // Size of blocks except the // last block is sq let sq = Math.sqrt(n); // Number of blocks to incorporate 1 to // n values blocks are numbered from 0 // to range-1 (both included) let range = Math.floor(n / sq) + 1; // Count array maintains the count for // all blocks let count = new Array(range).fill(0); // Traversing the read only array and // updating count for (let i = 0; i <= n; i++) { // arr[i] belongs to block number // (arr[i]-1)/sq i is considered // to start from 0 count[Math.floor((arr[i] - 1) / sq)]++; } // The selected_block is set to last // block by default. Rest of the blocks // are checked let selected_block = range - 1; for (let i = 0; i < range - 1; i++) { if (count[i] > sq) { selected_block = i; break; } } // after finding block with size > sq // method of hashing is used to find // the element repeating in this block let m = new Map(); for (let i = 0; i <= n; i++) { // checks if the element belongs to the // selected_block if (((selected_block * sq) < arr[i]) && (arr[i] <= ((selected_block + 1) * sq))) { m[arr[i]]++; if (m.has(arr[i])) { m.set(arr[i], m.get(arr[i]) + 1) } else { m.set(arr[i], 1) } // repeating element found if (m.get(arr[i]) > 1) return arr[i]; } } // return -1 if no repeating element exists return -1;} // Driver Program // read only array, not to be modifiedconst arr = [1, 1, 2, 3, 5, 4]; // array of size 6(n + 1) having// elements between 1 and 5let n = 5; document.write(\"One of the numbers repeated in\" + \" the array is: \" + findRepeatingNumber(arr, n) + \"<br>\"); </script>", "e": 40566, "s": 38528, "text": null }, { "code": null, "e": 40576, "s": 40566, "text": "Output: " }, { "code": null, "e": 40623, "s": 40576, "text": "One of the numbers repeated in the array is: 1" }, { "code": null, "e": 41090, "s": 40623, "text": "Time Complexity: O(N) Auxiliary Space: sqrt(N)This article is contributed by Aanya Jindal. 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": 41105, "s": 41090, "text": "sahilshelangia" }, { "code": null, "e": 41118, "s": 41105, "text": "rachana soma" }, { "code": null, "e": 41128, "s": 41118, "text": "Rajput-Ji" }, { "code": null, "e": 41145, "s": 41128, "text": "_saurabh_jaiswal" }, { "code": null, "e": 41163, "s": 41145, "text": "cpp-unordered_map" }, { "code": null, "e": 41170, "s": 41163, "text": "Arrays" }, { "code": null, "e": 41175, "s": 41170, "text": "Hash" }, { "code": null, "e": 41182, "s": 41175, "text": "Arrays" }, { "code": null, "e": 41187, "s": 41182, "text": "Hash" }, { "code": null, "e": 41285, "s": 41187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41353, "s": 41285, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 41397, "s": 41353, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 41445, "s": 41397, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 41468, "s": 41445, "text": "Introduction to Arrays" }, { "code": null, "e": 41500, "s": 41468, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 41585, "s": 41500, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 41612, "s": 41585, "text": "Count pairs with given sum" }, { "code": null, "e": 41643, "s": 41612, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 41677, "s": 41643, "text": "Hashing | Set 3 (Open Addressing)" } ]
Quadratic equation whose roots are K times the roots of given equation - GeeksforGeeks
13 May, 2021 Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0 and a positive integer K, the task is to find the coefficients of the quadratic equation whose roots are K times the roots of the given equation. Examples: Input: A = 1, B = 2, C = 1, K = 2Output: 1 4 4Explanation:The given quadratic equation x2 + 2x + 1 = 0.Roots of the above equation are -1, -1.Double of these roots are -2, -2.Therefore, the quadratic equation with the roots (-2, -2) is x2 + 4x + 4 = 0. Input: A = 1, B = -7, C = 12, K = 2Output: 1 -14 48 Approach: The given problem can be solved by using the concept of quadratic roots. Follow the steps below to solve the problem: Let the roots of the equation Ax2 + Bx + C = 0 be P and Q respectively. Then, the product of the roots of the above equation is given by P * Q = C / A and the sum of the roots of the above equation is given by P + Q = -B / A. Therefore, the product of the roots of the required equation is equal to: (K * P ) * (K * Q) = K2 * P * Q = (K2 * C ) / A Similarly, the sum of the roots of the required equation is 2 * K (-B / C). Therefore, the required quadratic equation is equal to: x2 – (Sum of the roots)x + (Product of the roots) = 0 => Ax2 + (KB)x + (K2)C = 0 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 quadratic// equation whose roots are K times// the roots of the given equationvoid findEquation(int A, int B, int C, int K){ // Print quadratic equation cout << A << " " << K * B << " " << K * K * C;} // Driver Codeint main(){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the quadratic// equation whose roots are K times// the roots of the given equationstatic void findEquation(int A, int B, int C, int K){ // Print quadratic equation System.out.print(A + " " + K * B + " " + K * K * C);} // Driver Codepublic static void main(String []args){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K);}} # Python3 program for the above approach # Function to find the quadratic# equation whose roots are K times# the roots of the given equationdef findEquation(A, B, C, K): # Prquadratic equation print(A, K*B, K*K*C) # Driver Codeif __name__ == '__main__': A, B, C, K = 1, 2, 1, 2 findEquation(A, B, C, K) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System; class GFG{ // Function to find the quadratic// equation whose roots are K times// the roots of the given equationstatic void findEquation(int A, int B, int C, int K){ // Print quadratic equation Console.Write(A + " " + K * B + " " + K * K * C);} // Driver Codepublic static void Main(){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K);}} // This code is contributed by ukasp <script>// Javascript program for the above approach // Function to find the quadratic// equation whose roots are K times// the roots of the given equationfunction findEquation(A, B, C, K){ // Print quadratic equation document.write( A + " " + K * B + " " + K * K * C);} // Driver Codevar A = 1, B = 2, C = 1, K = 2;findEquation(A, B, C, K); // This code is contributed by noob2000.</script> 1 4 4 Time Complexity: O(1)Auxiliary Space: O(1) mohit kumar 29 ukasp itsok noob2000 maths-power root Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26537, "s": 26509, "text": "\n13 May, 2021" }, { "code": null, "e": 26787, "s": 26537, "text": "Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0 and a positive integer K, the task is to find the coefficients of the quadratic equation whose roots are K times the roots of the given equation." }, { "code": null, "e": 26797, "s": 26787, "text": "Examples:" }, { "code": null, "e": 27050, "s": 26797, "text": "Input: A = 1, B = 2, C = 1, K = 2Output: 1 4 4Explanation:The given quadratic equation x2 + 2x + 1 = 0.Roots of the above equation are -1, -1.Double of these roots are -2, -2.Therefore, the quadratic equation with the roots (-2, -2) is x2 + 4x + 4 = 0." }, { "code": null, "e": 27102, "s": 27050, "text": "Input: A = 1, B = -7, C = 12, K = 2Output: 1 -14 48" }, { "code": null, "e": 27230, "s": 27102, "text": "Approach: The given problem can be solved by using the concept of quadratic roots. Follow the steps below to solve the problem:" }, { "code": null, "e": 27302, "s": 27230, "text": "Let the roots of the equation Ax2 + Bx + C = 0 be P and Q respectively." }, { "code": null, "e": 27456, "s": 27302, "text": "Then, the product of the roots of the above equation is given by P * Q = C / A and the sum of the roots of the above equation is given by P + Q = -B / A." }, { "code": null, "e": 27531, "s": 27456, "text": "Therefore, the product of the roots of the required equation is equal to: " }, { "code": null, "e": 27580, "s": 27531, "text": " (K * P ) * (K * Q) = K2 * P * Q = (K2 * C ) / A" }, { "code": null, "e": 27656, "s": 27580, "text": "Similarly, the sum of the roots of the required equation is 2 * K (-B / C)." }, { "code": null, "e": 27712, "s": 27656, "text": "Therefore, the required quadratic equation is equal to:" }, { "code": null, "e": 27767, "s": 27712, "text": " x2 – (Sum of the roots)x + (Product of the roots) = 0" }, { "code": null, "e": 27794, "s": 27767, "text": "=> Ax2 + (KB)x + (K2)C = 0" }, { "code": null, "e": 27845, "s": 27794, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27849, "s": 27845, "text": "C++" }, { "code": null, "e": 27854, "s": 27849, "text": "Java" }, { "code": null, "e": 27862, "s": 27854, "text": "Python3" }, { "code": null, "e": 27865, "s": 27862, "text": "C#" }, { "code": null, "e": 27876, "s": 27865, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the quadratic// equation whose roots are K times// the roots of the given equationvoid findEquation(int A, int B, int C, int K){ // Print quadratic equation cout << A << \" \" << K * B << \" \" << K * K * C;} // Driver Codeint main(){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K); return 0;}", "e": 28320, "s": 27876, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the quadratic// equation whose roots are K times// the roots of the given equationstatic void findEquation(int A, int B, int C, int K){ // Print quadratic equation System.out.print(A + \" \" + K * B + \" \" + K * K * C);} // Driver Codepublic static void main(String []args){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K);}}", "e": 28804, "s": 28320, "text": null }, { "code": "# Python3 program for the above approach # Function to find the quadratic# equation whose roots are K times# the roots of the given equationdef findEquation(A, B, C, K): # Prquadratic equation print(A, K*B, K*K*C) # Driver Codeif __name__ == '__main__': A, B, C, K = 1, 2, 1, 2 findEquation(A, B, C, K) # This code is contributed by mohit kumar 29.", "e": 29169, "s": 28804, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the quadratic// equation whose roots are K times// the roots of the given equationstatic void findEquation(int A, int B, int C, int K){ // Print quadratic equation Console.Write(A + \" \" + K * B + \" \" + K * K * C);} // Driver Codepublic static void Main(){ int A = 1, B = 2, C = 1, K = 2; findEquation(A, B, C, K);}} // This code is contributed by ukasp", "e": 29670, "s": 29169, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the quadratic// equation whose roots are K times// the roots of the given equationfunction findEquation(A, B, C, K){ // Print quadratic equation document.write( A + \" \" + K * B + \" \" + K * K * C);} // Driver Codevar A = 1, B = 2, C = 1, K = 2;findEquation(A, B, C, K); // This code is contributed by noob2000.</script>", "e": 30077, "s": 29670, "text": null }, { "code": null, "e": 30083, "s": 30077, "text": "1 4 4" }, { "code": null, "e": 30128, "s": 30085, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 30145, "s": 30130, "text": "mohit kumar 29" }, { "code": null, "e": 30151, "s": 30145, "text": "ukasp" }, { "code": null, "e": 30157, "s": 30151, "text": "itsok" }, { "code": null, "e": 30166, "s": 30157, "text": "noob2000" }, { "code": null, "e": 30178, "s": 30166, "text": "maths-power" }, { "code": null, "e": 30183, "s": 30178, "text": "root" }, { "code": null, "e": 30190, "s": 30183, "text": "Greedy" }, { "code": null, "e": 30203, "s": 30190, "text": "Mathematical" }, { "code": null, "e": 30210, "s": 30203, "text": "Greedy" }, { "code": null, "e": 30223, "s": 30210, "text": "Mathematical" }, { "code": null, "e": 30321, "s": 30223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30356, "s": 30321, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 30408, "s": 30356, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 30461, "s": 30408, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 30512, "s": 30461, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 30542, "s": 30512, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 30572, "s": 30542, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30615, "s": 30572, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 30630, "s": 30615, "text": "C++ Data Types" }, { "code": null, "e": 30654, "s": 30630, "text": "Merge two sorted arrays" } ]
How to set the Size of the ListBox in C#? - GeeksforGeeks
11 Jul, 2019 In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the height and width of the ListBox in pixels using Size Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the size of the ListBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ListBox control to set the size of the ListBox.Output: Output: 2. RunTime: It is a little bit trickier than the above method. In this method, you can set the size of the ListBox control programmatically with the help of given syntax: public System.Drawing.Size Size { get; set; } Here, Size indicates the height and width of the ListBox in pixels. The following steps show how to set the size of the ListBox dynamically: Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor ListBox mylist = new ListBox(); // Creating ListBox using ListBox class constructor ListBox mylist = new ListBox(); Step 2: After creating ListBox, set the Size property of the ListBox provided by the ListBox class.// Setting the size of the ListBox mylist.Size = new Size(120, 95); // Setting the size of the ListBox mylist.Size = new Size(120, 95); Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form this.Controls.Add(mylist); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output: // Add this ListBox to the form this.Controls.Add(mylist); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Class and Object C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Replace() Method
[ { "code": null, "e": 25819, "s": 25791, "text": "\n11 Jul, 2019" }, { "code": null, "e": 26217, "s": 25819, "text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you are allowed to set the height and width of the ListBox in pixels using Size Property of the ListBox which makes your ListBox more attractive. You can set this property in two different ways:" }, { "code": null, "e": 26319, "s": 26217, "text": "1. Design-Time: It is the easiest way to set the size of the ListBox as shown in the following steps:" }, { "code": null, "e": 26435, "s": 26319, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26614, "s": 26435, "text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need." }, { "code": null, "e": 26734, "s": 26614, "text": "Step 3: After drag and drop you will go to the properties of the ListBox control to set the size of the ListBox.Output:" }, { "code": null, "e": 26742, "s": 26734, "text": "Output:" }, { "code": null, "e": 26913, "s": 26742, "text": "2. RunTime: It is a little bit trickier than the above method. In this method, you can set the size of the ListBox control programmatically with the help of given syntax:" }, { "code": null, "e": 26959, "s": 26913, "text": "public System.Drawing.Size Size { get; set; }" }, { "code": null, "e": 27100, "s": 26959, "text": "Here, Size indicates the height and width of the ListBox in pixels. The following steps show how to set the size of the ListBox dynamically:" }, { "code": null, "e": 27276, "s": 27100, "text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 27361, "s": 27276, "text": "// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 27530, "s": 27361, "text": "Step 2: After creating ListBox, set the Size property of the ListBox provided by the ListBox class.// Setting the size of the ListBox\n mylist.Size = new Size(120, 95);\n" }, { "code": null, "e": 27600, "s": 27530, "text": "// Setting the size of the ListBox\n mylist.Size = new Size(120, 95);\n" }, { "code": null, "e": 28556, "s": 27600, "text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(mylist);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output:" }, { "code": null, "e": 28616, "s": 28556, "text": "// Add this ListBox to the form\nthis.Controls.Add(mylist);\n" }, { "code": null, "e": 28625, "s": 28616, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // the properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.ForeColor = Color.Purple; mylist.Items.Add(123); mylist.Items.Add(456); mylist.Items.Add(789); // Adding ListBox control to the form this.Controls.Add(mylist); }}}", "e": 29434, "s": 28625, "text": null }, { "code": null, "e": 29442, "s": 29434, "text": "Output:" }, { "code": null, "e": 29445, "s": 29442, "text": "C#" }, { "code": null, "e": 29543, "s": 29445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29571, "s": 29543, "text": "C# Dictionary with examples" }, { "code": null, "e": 29586, "s": 29571, "text": "C# | Delegates" }, { "code": null, "e": 29609, "s": 29586, "text": "C# | Method Overriding" }, { "code": null, "e": 29631, "s": 29609, "text": "C# | Abstract Classes" }, { "code": null, "e": 29677, "s": 29631, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29699, "s": 29677, "text": "C# | Class and Object" }, { "code": null, "e": 29717, "s": 29699, "text": "C# | Constructors" }, { "code": null, "e": 29740, "s": 29717, "text": "Extension Method in C#" }, { "code": null, "e": 29771, "s": 29740, "text": "Introduction to .NET Framework" } ]
Longest non-decreasing subsequence having difference between adjacent elements less than D - GeeksforGeeks
27 Oct, 2021 Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D. Examples: Input: arr[] = {1, 3, 2, 4, 5}, D = 2Output: 3Explanation:Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the given criteria. Input: arr[] = {1, 5, 3, 2, 7}, D = 2Output: 2 Approach: The given problem is a variation of Longest Increasing Subsequence with criteria for the difference between adjacent array elements as less than D, this idea can be implemented using Dynamic Programming. Follow the steps below to solve the given problem: Initialize a dp array, where dp[i] will store the maximum length of non-decreasing subsequence after including the ith element such that the difference between every adjacent pair of elements is less than D. Initialize all values of the array dp[] as 1. Iterate a loop over the range [0, N] and in each iteration, i traverse the given array arr[] over the range [0, i – 1] using the variable j and if the value of arr[j] is at least arr[i] and the difference between them is less than D, then update the value of dp[i] to the maximum of dp[i] and (1 + dp[j]). After completing the above steps, print the maximum value of the array dp[] as the result. 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 return the length of the // longest non-decreasing subsequence // having the difference as D for every // adjacent elements int longestSubsequence(vector<int> arr, int d) { // Store the size of array int n = arr.size(); // Stores the maximum length of the // subsequence after including the // ith element vector<int> dp(n, 1); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { // If it satisfies the // given condition if (arr[i] - d < arr[j] and arr[i] >= arr[j]) { // Update dp[i] dp[i] = max(dp[i], dp[j] + 1); } } } // Maximum value in the dp // table is the answer return *max_element( dp.begin(), dp.end()); } // Driver Code int main() { vector<int> arr = { 1, 3, 2, 4, 5 }; int D = 2; cout << longestSubsequence(arr, D); return 0; } // Java program for the above approach import java.util.*; public class GFG { // Function to return the length of the // longest non-decreasing subsequence // having the difference as D for every // adjacent elements static int longestSubsequence(int []arr, int d) { // Store the size of array int n = arr.length; // Stores the maximum length of the // subsequence after including the // ith element int []dp = new int[n]; for(int i = 0; i < n ; i++) dp[i] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { // If it satisfies the // given condition if (arr[i] - d < arr[j] && arr[i] >= arr[j]) { // Update dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } } } // Maximum value in the dp // table is the answer Arrays.sort(dp); return dp[n - 1]; } // Driver Code public static void main (String[] args) { int arr[] = { 1, 3, 2, 4, 5 }; int D = 2; System.out.println(longestSubsequence(arr, D)); } } // This code is contributed by AnkThon # python program for the above approach # Function to return the length of the # longest non-decreasing subsequence # having the difference as D for every # adjacent elements def longestSubsequence(arr, d): # Store the size of array n = len(arr) # Stores the maximum length of the # subsequence after including the # ith element dp = [1 for _ in range(n)] for i in range(0, n): for j in range(0, i): # If it satisfies the # given condition if (arr[i] - d < arr[j] and arr[i] >= arr[j]): # Update dp[i] dp[i] = max(dp[i], dp[j] + 1) # Maximum value in the dp # table is the answer return max(dp) # Driver Code if __name__ == "__main__": arr = [1, 3, 2, 4, 5] D = 2 print(longestSubsequence(arr, D)) # This code is contributed by rakeshsahni // C# program for the above approach using System; public class GFG { // Function to return the length of the // longest non-decreasing subsequence // having the difference as D for every // adjacent elements static int longestSubsequence(int []arr, int d) { // Store the size of array int n = arr.Length; // Stores the maximum length of the // subsequence after including the // ith element int []dp = new int[n]; for(int i = 0; i < n ; i++) dp[i] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { // If it satisfies the // given condition if (arr[i] - d < arr[j] && arr[i] >= arr[j]) { // Update dp[i] dp[i] = Math.Max(dp[i], dp[j] + 1); } } } // Maximum value in the dp // table is the answer Array.Sort(dp); return dp[n - 1]; } // Driver Code public static void Main (string[] args) { int []arr = { 1, 3, 2, 4, 5 }; int D = 2; Console.WriteLine(longestSubsequence(arr, D)); } } // This code is contributed by AnkThon <script> // Javascript program for the above approach // Function to return the length of the // longest non-decreasing subsequence // having the difference as D for every // adjacent elements function longestSubsequence(arr, d) { // Store the size of array let n = arr.length; // Stores the maximum length of the // subsequence after including the // ith element let dp = new Array(n).fill(1); for (let i = 0; i < n; i++) { for (let j = 0; j < i; j++) { // If it satisfies the // given condition if (arr[i] - d < arr[j] && arr[i] >= arr[j]) { // Update dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } } } // Maximum value in the dp // table is the answer return dp.sort((a, b) => b - a)[0]; } // Driver Code let arr = [1, 3, 2, 4, 5]; let D = 2; document.write(longestSubsequence(arr, D)); // This code is contributed by gfgking. </script> 3 Time Complexity: O(N2)Auxiliary Space: O(N) rakeshsahni gfgking ankthon LIS subsequence Arrays Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26115, "s": 26084, "text": " \n27 Oct, 2021\n" }, { "code": null, "e": 26313, "s": 26115, "text": "Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D." }, { "code": null, "e": 26323, "s": 26313, "text": "Examples:" }, { "code": null, "e": 26482, "s": 26323, "text": "Input: arr[] = {1, 3, 2, 4, 5}, D = 2Output: 3Explanation:Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the given criteria." }, { "code": null, "e": 26529, "s": 26482, "text": "Input: arr[] = {1, 5, 3, 2, 7}, D = 2Output: 2" }, { "code": null, "e": 26794, "s": 26529, "text": "Approach: The given problem is a variation of Longest Increasing Subsequence with criteria for the difference between adjacent array elements as less than D, this idea can be implemented using Dynamic Programming. Follow the steps below to solve the given problem:" }, { "code": null, "e": 27002, "s": 26794, "text": "Initialize a dp array, where dp[i] will store the maximum length of non-decreasing subsequence after including the ith element such that the difference between every adjacent pair of elements is less than D." }, { "code": null, "e": 27048, "s": 27002, "text": "Initialize all values of the array dp[] as 1." }, { "code": null, "e": 27354, "s": 27048, "text": "Iterate a loop over the range [0, N] and in each iteration, i traverse the given array arr[] over the range [0, i – 1] using the variable j and if the value of arr[j] is at least arr[i] and the difference between them is less than D, then update the value of dp[i] to the maximum of dp[i] and (1 + dp[j])." }, { "code": null, "e": 27445, "s": 27354, "text": "After completing the above steps, print the maximum value of the array dp[] as the result." }, { "code": null, "e": 27496, "s": 27445, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27500, "s": 27496, "text": "C++" }, { "code": null, "e": 27505, "s": 27500, "text": "Java" }, { "code": null, "e": 27513, "s": 27505, "text": "Python3" }, { "code": null, "e": 27516, "s": 27513, "text": "C#" }, { "code": null, "e": 27527, "s": 27516, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for the above approach\n \n#include <bits/stdc++.h>\nusing namespace std;\n \n// Function to return the length of the\n// longest non-decreasing subsequence\n// having the difference as D for every\n// adjacent elements\nint longestSubsequence(vector<int> arr,\n int d)\n{\n // Store the size of array\n int n = arr.size();\n \n // Stores the maximum length of the\n // subsequence after including the\n // ith element\n vector<int> dp(n, 1);\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < i; j++) {\n \n // If it satisfies the\n // given condition\n if (arr[i] - d < arr[j]\n and arr[i] >= arr[j]) {\n \n // Update dp[i]\n dp[i] = max(dp[i], dp[j] + 1);\n }\n }\n }\n \n // Maximum value in the dp\n // table is the answer\n return *max_element(\n dp.begin(), dp.end());\n}\n \n// Driver Code\nint main()\n{\n vector<int> arr = { 1, 3, 2, 4, 5 };\n int D = 2;\n cout << longestSubsequence(arr, D);\n \n return 0;\n}\n\n\n\n\n\n", "e": 28621, "s": 27537, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for the above approach\nimport java.util.*;\npublic class GFG {\n \n // Function to return the length of the\n // longest non-decreasing subsequence\n // having the difference as D for every\n // adjacent elements\n static int longestSubsequence(int []arr,\n int d)\n {\n \n // Store the size of array\n int n = arr.length;\n \n // Stores the maximum length of the\n // subsequence after including the\n // ith element\n int []dp = new int[n];\n \n for(int i = 0; i < n ; i++)\n dp[i] = 1;\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < i; j++) {\n \n // If it satisfies the\n // given condition\n if (arr[i] - d < arr[j] && arr[i] >= arr[j]) {\n \n // Update dp[i]\n dp[i] = Math.max(dp[i], dp[j] + 1);\n }\n }\n }\n \n // Maximum value in the dp\n // table is the answer\n Arrays.sort(dp);\n return dp[n - 1];\n }\n \n // Driver Code\n public static void main (String[] args) {\n int arr[] = { 1, 3, 2, 4, 5 };\n int D = 2;\n System.out.println(longestSubsequence(arr, D));\n }\n} \n \n// This code is contributed by AnkThon\n\n\n\n\n\n", "e": 29989, "s": 28631, "text": null }, { "code": "\n\n\n\n\n\n\n# python program for the above approach\n \n# Function to return the length of the\n# longest non-decreasing subsequence\n# having the difference as D for every\n# adjacent elements\ndef longestSubsequence(arr, d):\n \n # Store the size of array\n n = len(arr)\n \n # Stores the maximum length of the\n # subsequence after including the\n # ith element\n dp = [1 for _ in range(n)]\n \n for i in range(0, n):\n for j in range(0, i):\n \n # If it satisfies the\n # given condition\n if (arr[i] - d < arr[j] and arr[i] >= arr[j]):\n \n # Update dp[i]\n dp[i] = max(dp[i], dp[j] + 1)\n \n # Maximum value in the dp\n # table is the answer\n return max(dp)\n \n# Driver Code\nif __name__ == \"__main__\":\n \n arr = [1, 3, 2, 4, 5]\n D = 2\n print(longestSubsequence(arr, D))\n \n # This code is contributed by rakeshsahni\n\n\n\n\n\n", "e": 30904, "s": 29999, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for the above approach\nusing System;\n \npublic class GFG {\n \n // Function to return the length of the\n // longest non-decreasing subsequence\n // having the difference as D for every\n // adjacent elements\n static int longestSubsequence(int []arr,\n int d)\n {\n \n // Store the size of array\n int n = arr.Length;\n \n // Stores the maximum length of the\n // subsequence after including the\n // ith element\n int []dp = new int[n];\n \n for(int i = 0; i < n ; i++)\n dp[i] = 1;\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < i; j++) {\n \n // If it satisfies the\n // given condition\n if (arr[i] - d < arr[j] && arr[i] >= arr[j]) {\n \n // Update dp[i]\n dp[i] = Math.Max(dp[i], dp[j] + 1);\n }\n }\n }\n \n // Maximum value in the dp\n // table is the answer\n Array.Sort(dp);\n return dp[n - 1];\n }\n \n // Driver Code\n public static void Main (string[] args) {\n int []arr = { 1, 3, 2, 4, 5 };\n int D = 2;\n Console.WriteLine(longestSubsequence(arr, D));\n }\n} \n \n// This code is contributed by AnkThon\n\n\n\n\n\n", "e": 32264, "s": 30914, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// Javascript program for the above approach\n \n// Function to return the length of the\n// longest non-decreasing subsequence\n// having the difference as D for every\n// adjacent elements\nfunction longestSubsequence(arr, d) \n{\n \n // Store the size of array\n let n = arr.length;\n \n // Stores the maximum length of the\n // subsequence after including the\n // ith element\n let dp = new Array(n).fill(1);\n \n for (let i = 0; i < n; i++)\n {\n for (let j = 0; j < i; j++)\n {\n \n // If it satisfies the\n // given condition\n if (arr[i] - d < arr[j] && arr[i] >= arr[j])\n {\n \n // Update dp[i]\n dp[i] = Math.max(dp[i], dp[j] + 1);\n }\n }\n }\n \n // Maximum value in the dp\n // table is the answer\n return dp.sort((a, b) => b - a)[0];\n}\n \n// Driver Code\nlet arr = [1, 3, 2, 4, 5];\nlet D = 2;\ndocument.write(longestSubsequence(arr, D));\n \n// This code is contributed by gfgking.\n</script>\n\n\n\n\n\n", "e": 33235, "s": 32274, "text": null }, { "code": null, "e": 33240, "s": 33238, "text": "3" }, { "code": null, "e": 33288, "s": 33244, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 33302, "s": 33290, "text": "rakeshsahni" }, { "code": null, "e": 33310, "s": 33302, "text": "gfgking" }, { "code": null, "e": 33318, "s": 33310, "text": "ankthon" }, { "code": null, "e": 33324, "s": 33318, "text": "\nLIS\n" }, { "code": null, "e": 33338, "s": 33324, "text": "\nsubsequence\n" }, { "code": null, "e": 33347, "s": 33338, "text": "\nArrays\n" }, { "code": null, "e": 33369, "s": 33347, "text": "\nDynamic Programming\n" }, { "code": null, "e": 33384, "s": 33369, "text": "\nMathematical\n" }, { "code": null, "e": 33589, "s": 33384, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 33620, "s": 33589, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33647, "s": 33620, "text": "Count pairs with given sum" }, { "code": null, "e": 33672, "s": 33647, "text": "Window Sliding Technique" }, { "code": null, "e": 33710, "s": 33672, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33731, "s": 33710, "text": "Next Greater Element" }, { "code": null, "e": 33760, "s": 33731, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 33790, "s": 33760, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33824, "s": 33790, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33855, "s": 33824, "text": "Bellman–Ford Algorithm | DP-23" } ]
Repeat Character String N Times in R - GeeksforGeeks
09 Feb, 2022 In this article, we will discuss how to repeat the character string N times in the R programming language. Character string means a set of characters . Example: “Hello Geek”,”Python”,”Languages_Python” are some examples This function used to give n replicas from the character string Syntax: replicate(N, “string”) where, N is the number of times string is replicated string is the input character string Example: R program to repeat the character string N times using replicate R # get 2 timesprint(replicate(2, "Hello_Geek")) print("-----") # get 10 timesprint(replicate(10, "Python")) print("-----") # get 3 timesprint(replicate(3, "java")) print("-----") # get 4 timesprint(replicate(4, "dbms")) print("-----") # get 5 timesprint(replicate(5, "sql")) print("-----") # get 7 timesprint(replicate(7, "big data")) Output: [1] “Hello_Geek” “Hello_Geek” [1] “—–“ [1] “Python” “Python” “Python” “Python” “Python” “Python” “Python” “Python” [9] “Python” “Python” [1] “—–“ [1] “java” “java” “java” [1] “—–“ [1] “dbms” “dbms” “dbms” “dbms” [1] “—–“ [1] “sql” “sql” “sql” “sql” “sql” [1] “—–“ [1] “big data” “big data” “big data” “big data” “big data” “big data” “big data” This function works similar to replicate . Syntax: rep( “string”,N) Example: R program that repeats character String N times using rep R # get 2 timesprint(rep("Hello_Geek", 2)) print("-----") # get 10 timesprint(rep("Python", 10)) print("-----") # get 3 timesprint(rep("java", 3)) print("-----") # get 4 timesprint(rep("dbms", 4)) print("-----") # get 5 timesprint(rep("sql", 5)) print("-----") # get 7 timesprint(rep("big data", 7)) Output: [1] “Hello_Geek” “Hello_Geek” [1] “—–“ [1] “Python” “Python” “Python” “Python” “Python” “Python” “Python” “Python” [9] “Python” “Python” [1] “—–“ [1] “java” “java” “java” [1] “—–“ [1] “dbms” “dbms” “dbms” “dbms” [1] “—–“ [1] “sql” “sql” “sql” “sql” “sql” [1] “—–“ [1] “big data” “big data” “big data” “big data” “big data” “big data” “big data” This paste is used to organize the repeated strings in the correct way, It will separate the strings with the given delimiter. Syntax: paste(replicate(N, “string”), collapse = “delimiter”) where, paste is used to display the data replicate is used to get the N character strings collapse is used to separate the strings Example: R program to repeat the character strings using paste command R # get 2 times with delimiter --paste(replicate(2, "Geek"), collapse = "--") print("-----") # get 10 times with delimiter ,paste(replicate(2, "Python"), collapse = ",") Output: [1] “Geek–Geek” [1] “—–“ [1] “Python,Python” This function is used to get the N character strings in a single string. Syntax: strrep( “string”,N) Example: R program to get N character strings using strrep() function R # get 2 timesprint(strrep( "Hello_Geek",2)) print("-----") # get 10 timesprint(strrep( "Python",10)) print("-----") # get 3 timesprint(strrep( "java",3)) print("-----") # get 4 timesprint(strrep("dbms",4)) print("-----") # get 5 timesprint(strrep( "sql",5)) print("-----") # get 7 timesprint(strrep("big data",7)) Output: [1] “Hello_GeekHello_Geek” [1] “—–“ [1] “PythonPythonPythonPythonPythonPythonPythonPythonPythonPython” [1] “—–“ [1] “javajavajava” [1] “—–“ [1] “dbmsdbmsdbmsdbms” [1] “—–“ [1] “sqlsqlsqlsqlsql” [1] “—–“ [1] “big databig databig databig databig databig databig data” simmytarika5 varshagumber28 Picked R String-Programs R-strings R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Hierarchical Clustering in R Programming How to Change Axis Scales in R Plots? Group by function in R using Dplyr Naive Bayes Classifier in R Programming How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n09 Feb, 2022" }, { "code": null, "e": 26639, "s": 26487, "text": "In this article, we will discuss how to repeat the character string N times in the R programming language. Character string means a set of characters ." }, { "code": null, "e": 26648, "s": 26639, "text": "Example:" }, { "code": null, "e": 26707, "s": 26648, "text": "“Hello Geek”,”Python”,”Languages_Python” are some examples" }, { "code": null, "e": 26771, "s": 26707, "text": "This function used to give n replicas from the character string" }, { "code": null, "e": 26779, "s": 26771, "text": "Syntax:" }, { "code": null, "e": 26802, "s": 26779, "text": "replicate(N, “string”)" }, { "code": null, "e": 26809, "s": 26802, "text": "where," }, { "code": null, "e": 26855, "s": 26809, "text": "N is the number of times string is replicated" }, { "code": null, "e": 26892, "s": 26855, "text": "string is the input character string" }, { "code": null, "e": 26966, "s": 26892, "text": "Example: R program to repeat the character string N times using replicate" }, { "code": null, "e": 26968, "s": 26966, "text": "R" }, { "code": "# get 2 timesprint(replicate(2, \"Hello_Geek\")) print(\"-----\") # get 10 timesprint(replicate(10, \"Python\")) print(\"-----\") # get 3 timesprint(replicate(3, \"java\")) print(\"-----\") # get 4 timesprint(replicate(4, \"dbms\")) print(\"-----\") # get 5 timesprint(replicate(5, \"sql\")) print(\"-----\") # get 7 timesprint(replicate(7, \"big data\"))", "e": 27302, "s": 26968, "text": null }, { "code": null, "e": 27313, "s": 27305, "text": "Output:" }, { "code": null, "e": 27345, "s": 27315, "text": "[1] “Hello_Geek” “Hello_Geek”" }, { "code": null, "e": 27354, "s": 27345, "text": "[1] “—–“" }, { "code": null, "e": 27430, "s": 27354, "text": "[1] “Python” “Python” “Python” “Python” “Python” “Python” “Python” “Python”" }, { "code": null, "e": 27452, "s": 27430, "text": "[9] “Python” “Python”" }, { "code": null, "e": 27461, "s": 27452, "text": "[1] “—–“" }, { "code": null, "e": 27486, "s": 27461, "text": "[1] “java” “java” “java”" }, { "code": null, "e": 27495, "s": 27486, "text": "[1] “—–“" }, { "code": null, "e": 27527, "s": 27495, "text": "[1] “dbms” “dbms” “dbms” “dbms”" }, { "code": null, "e": 27536, "s": 27527, "text": "[1] “—–“" }, { "code": null, "e": 27570, "s": 27536, "text": "[1] “sql” “sql” “sql” “sql” “sql”" }, { "code": null, "e": 27579, "s": 27570, "text": "[1] “—–“" }, { "code": null, "e": 27660, "s": 27579, "text": "[1] “big data” “big data” “big data” “big data” “big data” “big data” “big data”" }, { "code": null, "e": 27705, "s": 27662, "text": "This function works similar to replicate ." }, { "code": null, "e": 27715, "s": 27707, "text": "Syntax:" }, { "code": null, "e": 27734, "s": 27717, "text": "rep( “string”,N)" }, { "code": null, "e": 27803, "s": 27736, "text": "Example: R program that repeats character String N times using rep" }, { "code": null, "e": 27807, "s": 27805, "text": "R" }, { "code": "# get 2 timesprint(rep(\"Hello_Geek\", 2)) print(\"-----\") # get 10 timesprint(rep(\"Python\", 10)) print(\"-----\") # get 3 timesprint(rep(\"java\", 3)) print(\"-----\") # get 4 timesprint(rep(\"dbms\", 4)) print(\"-----\") # get 5 timesprint(rep(\"sql\", 5)) print(\"-----\") # get 7 timesprint(rep(\"big data\", 7))", "e": 28105, "s": 27807, "text": null }, { "code": null, "e": 28113, "s": 28105, "text": "Output:" }, { "code": null, "e": 28143, "s": 28113, "text": "[1] “Hello_Geek” “Hello_Geek”" }, { "code": null, "e": 28152, "s": 28143, "text": "[1] “—–“" }, { "code": null, "e": 28228, "s": 28152, "text": "[1] “Python” “Python” “Python” “Python” “Python” “Python” “Python” “Python”" }, { "code": null, "e": 28250, "s": 28228, "text": "[9] “Python” “Python”" }, { "code": null, "e": 28259, "s": 28250, "text": "[1] “—–“" }, { "code": null, "e": 28284, "s": 28259, "text": "[1] “java” “java” “java”" }, { "code": null, "e": 28293, "s": 28284, "text": "[1] “—–“" }, { "code": null, "e": 28325, "s": 28293, "text": "[1] “dbms” “dbms” “dbms” “dbms”" }, { "code": null, "e": 28334, "s": 28325, "text": "[1] “—–“" }, { "code": null, "e": 28368, "s": 28334, "text": "[1] “sql” “sql” “sql” “sql” “sql”" }, { "code": null, "e": 28377, "s": 28368, "text": "[1] “—–“" }, { "code": null, "e": 28458, "s": 28377, "text": "[1] “big data” “big data” “big data” “big data” “big data” “big data” “big data”" }, { "code": null, "e": 28585, "s": 28458, "text": "This paste is used to organize the repeated strings in the correct way, It will separate the strings with the given delimiter." }, { "code": null, "e": 28593, "s": 28585, "text": "Syntax:" }, { "code": null, "e": 28647, "s": 28593, "text": "paste(replicate(N, “string”), collapse = “delimiter”)" }, { "code": null, "e": 28654, "s": 28647, "text": "where," }, { "code": null, "e": 28688, "s": 28654, "text": "paste is used to display the data" }, { "code": null, "e": 28737, "s": 28688, "text": "replicate is used to get the N character strings" }, { "code": null, "e": 28778, "s": 28737, "text": "collapse is used to separate the strings" }, { "code": null, "e": 28849, "s": 28778, "text": "Example: R program to repeat the character strings using paste command" }, { "code": null, "e": 28851, "s": 28849, "text": "R" }, { "code": "# get 2 times with delimiter --paste(replicate(2, \"Geek\"), collapse = \"--\") print(\"-----\") # get 10 times with delimiter ,paste(replicate(2, \"Python\"), collapse = \",\")", "e": 29019, "s": 28851, "text": null }, { "code": null, "e": 29027, "s": 29019, "text": "Output:" }, { "code": null, "e": 29043, "s": 29027, "text": "[1] “Geek–Geek”" }, { "code": null, "e": 29052, "s": 29043, "text": "[1] “—–“" }, { "code": null, "e": 29072, "s": 29052, "text": "[1] “Python,Python”" }, { "code": null, "e": 29145, "s": 29072, "text": "This function is used to get the N character strings in a single string." }, { "code": null, "e": 29153, "s": 29145, "text": "Syntax:" }, { "code": null, "e": 29173, "s": 29153, "text": "strrep( “string”,N)" }, { "code": null, "e": 29243, "s": 29173, "text": "Example: R program to get N character strings using strrep() function" }, { "code": null, "e": 29245, "s": 29243, "text": "R" }, { "code": "# get 2 timesprint(strrep( \"Hello_Geek\",2)) print(\"-----\") # get 10 timesprint(strrep( \"Python\",10)) print(\"-----\") # get 3 timesprint(strrep( \"java\",3)) print(\"-----\") # get 4 timesprint(strrep(\"dbms\",4)) print(\"-----\") # get 5 timesprint(strrep( \"sql\",5)) print(\"-----\") # get 7 timesprint(strrep(\"big data\",7))", "e": 29559, "s": 29245, "text": null }, { "code": null, "e": 29570, "s": 29562, "text": "Output:" }, { "code": null, "e": 29599, "s": 29572, "text": "[1] “Hello_GeekHello_Geek”" }, { "code": null, "e": 29608, "s": 29599, "text": "[1] “—–“" }, { "code": null, "e": 29675, "s": 29608, "text": "[1] “PythonPythonPythonPythonPythonPythonPythonPythonPythonPython”" }, { "code": null, "e": 29684, "s": 29675, "text": "[1] “—–“" }, { "code": null, "e": 29703, "s": 29684, "text": "[1] “javajavajava”" }, { "code": null, "e": 29712, "s": 29703, "text": "[1] “—–“" }, { "code": null, "e": 29735, "s": 29712, "text": "[1] “dbmsdbmsdbmsdbms”" }, { "code": null, "e": 29744, "s": 29735, "text": "[1] “—–“" }, { "code": null, "e": 29766, "s": 29744, "text": "[1] “sqlsqlsqlsqlsql”" }, { "code": null, "e": 29775, "s": 29766, "text": "[1] “—–“" }, { "code": null, "e": 29838, "s": 29775, "text": "[1] “big databig databig databig databig databig databig data”" }, { "code": null, "e": 29853, "s": 29840, "text": "simmytarika5" }, { "code": null, "e": 29868, "s": 29853, "text": "varshagumber28" }, { "code": null, "e": 29875, "s": 29868, "text": "Picked" }, { "code": null, "e": 29893, "s": 29875, "text": "R String-Programs" }, { "code": null, "e": 29903, "s": 29893, "text": "R-strings" }, { "code": null, "e": 29914, "s": 29903, "text": "R Language" }, { "code": null, "e": 29925, "s": 29914, "text": "R Programs" }, { "code": null, "e": 30023, "s": 29925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30075, "s": 30023, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30116, "s": 30075, "text": "Hierarchical Clustering in R Programming" }, { "code": null, "e": 30154, "s": 30116, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30189, "s": 30154, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30229, "s": 30189, "text": "Naive Bayes Classifier in R Programming" }, { "code": null, "e": 30287, "s": 30229, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30330, "s": 30287, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30379, "s": 30330, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30429, "s": 30379, "text": "How to filter R dataframe by multiple conditions?" } ]
Accessing Protected Members in Java - GeeksforGeeks
24 Sep, 2021 In Java, there are four types of access modifiers. These are public, private, default, and protected. To get the idea of these modifiers, you can refer to access modifiers in java. In this article, we discuss the accessibility of protected members in different cases. Now let us discuss various scenarios of accessing protected members which are listed below as follows: Accessing in the same classAccessing in other classes of the same packageAccessing protected members of a class in its subclass in the same packageAccessing another class in a different packageAccessing in sub-class in a different package Accessing in the same class Accessing in other classes of the same package Accessing protected members of a class in its subclass in the same package Accessing another class in a different package Accessing in sub-class in a different package Case 1: Accessing protected members in the same class We can access protected members of a class anywhere in it. Example: Java // Java Program to Illustrate// Accessing Protected Members// in the same class // Main class class Sample { protected int year = 2021; protected void printYear() { System.out.println("Its " + year + " !!"); } public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); }} 2021 Its 2021 !! Case 2: Accessing protected members in other classes of the same package We can access protected members of a class in another class that is present in the same package. Java // Java Program to Illustrate Accessing// Protected Members// In Other Class of Same Package // Class 1class Sample { protected int year = 2021; protected void printYear() { System.out.println("Its "+year+" !!"); }} // Class 2public class Test { // Main driver method public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); }} 2021 Its 2021 !! Case 3: Accessing protected members of a class in its subclass in the same package We can access protected members of a class in its subclass if both are present in the same package. Example Java // Java Program to Illustrate// Accessing Protected Members// of a class in its subclass// in the same package // Class 1class Sample { static protected String title = "geekforgeeks"; protected int year = 2021; protected void printYear() { System.out.println("Its "+year+" !!"); }} // Class 2public class Test extends Sample { public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); System.out.println(Sample.title); }} 2021 Its 2021 !! geekforgeeks Case 4: Accessing protected members in another class in a different package We cannot access the protected members of a class in a class (non-subclass) that is present in a different package. Example 1: Package 1 Java // Java Program to Illustrate// Accessing Protected Members// In Another Class in a// Different Package // Package 1package package1; // Main classpublic class Sample { static protected String title = "geeksforgeeks"; protected int year = 2021; // Protected method protected void printYear() { System.out.println("Its "+year+" !!"); }} Example 2: Package 2 Java // Java Program to Illustrate// Accessing Protected Members// In Another Class in a// Different Package // Package 1package package2;// Importing above packageimport package1.Sample; // Main classpublic class Test { // Main driver method public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); System.out.println(Sample.title); }} Output: error: year has protected access in Sample System.out.println(sample.year); ^ error: printYear() has protected access in Sample sample.printYear(); ^ error: title has protected access in Sample System.out.println(Sample.title); ^ It will give a compile-time error. In the following example, we will create two classes. Sample class in package1 and Test class in package2 and try to access protected members of Sample class in Test class. It is justified in the above two examples. Case 5: Accessing protected members in sub-class in a different package We can access protected members of a class in its subclass present in a different package. In the following example, we will create two classes. Sample class in package1 and Child class in package2. Child class extends Sample class. Example 1.1 Java // Java Program to Illustrate Accessing Protected// Members in sub-class in a different package package package1; // Classpublic class Sample { // Protected attributes static protected String title = "geeksforgeeks"; protected int year = 2021; protected void printYear() { System.out.println("Its " + year + " !!"); }} Example 1.2 Java // Java Program to Illustrate Accessing Protected// Members in Sub-class in a different Packagepackage package2;// Importing class from above packageimport package1.Sample; // Main classpublic class Child extends Sample { // Method 1 void helper() { System.out.println(year); printYear(); System.out.println(Sample.title); } // Method 2 // Main driver method public static void main(String[] args) { // Creating child class instance inside main() Child child = new Child(); child.helper(); }} Output 2021 Its 2021 !! geeksforgeeks Note: From the above output it can be perceived we have successfully accessed the protected members directly as these are inherited by the Child class and can be accessed without using any reference. The protected members are inherited by the child classes and can access them as its own members. But we can’t access these members using the reference of the parent class. We can access protected members only by using child class reference. Example 2 Java // Java Program to Illustrate Compile-time Error Thrown// When we are Trying to Access Protected Members// Using Parent Class Reference // Importing packagespackage package2;import package1.Sample; // Importing class extending to Parent classpublic class Child extends Sample { // Method 1 void helper() { // Creating instance of Child class inside main() Child myself = new Child(); // As Child is sub-class of Sample, we can access // the static variable here System.out.println(Sample.title); // This will compile fine as we are accessing year // using child class reference variable System.out.println(year); System.out.println(myself.year); // This will compile fine as we are accessing // printYear() method using child class reference // variable printYear(); myself.printYear(); // Creating parent class object Sample sample = new Sample(); // Parent class reference holding child class object Sample child = new Child(); // Note: Below lines of code won't compile as we are // trying to access protected members of parent // class using Parent's class reference which is // present in other package // Errors will be thrown System.out.println(sample.year); sample.printYear(); child.printYear(); } // Method 2 // Main driver method public static void main(String[] args) { // Creating child class instance inside main() Child child = new Child(); // Calling the above method 1 of child class child.helper(); }} Output error: year has protected access in Sample System.out.println(sample.year); ^ error: printYear() has protected access in Sample sample.printYear(); ^ error: printYear() has protected access in Sample child.printYear(); ^ So the main difference between default access modifiers and the protected modifier is that default members are accessible only in the current package. While protected members can be accessed anywhere in the same package and outside package only in its child class and using the child class’s reference variable only, not on the reference variable of the parent class. We can’t access protected members using the parent class’s reference. sweetyty simranarora5sos access modifiers Blogathon-2021 java-basics Blogathon Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date How to Install Tkinter in Windows? How to Create a Table With Multiple Foreign Keys in SQL? SQL Query to Create Table With a Primary Key Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24812, "s": 24784, "text": "\n24 Sep, 2021" }, { "code": null, "e": 25080, "s": 24812, "text": "In Java, there are four types of access modifiers. These are public, private, default, and protected. To get the idea of these modifiers, you can refer to access modifiers in java. In this article, we discuss the accessibility of protected members in different cases." }, { "code": null, "e": 25183, "s": 25080, "text": "Now let us discuss various scenarios of accessing protected members which are listed below as follows:" }, { "code": null, "e": 25422, "s": 25183, "text": "Accessing in the same classAccessing in other classes of the same packageAccessing protected members of a class in its subclass in the same packageAccessing another class in a different packageAccessing in sub-class in a different package" }, { "code": null, "e": 25450, "s": 25422, "text": "Accessing in the same class" }, { "code": null, "e": 25497, "s": 25450, "text": "Accessing in other classes of the same package" }, { "code": null, "e": 25572, "s": 25497, "text": "Accessing protected members of a class in its subclass in the same package" }, { "code": null, "e": 25619, "s": 25572, "text": "Accessing another class in a different package" }, { "code": null, "e": 25665, "s": 25619, "text": "Accessing in sub-class in a different package" }, { "code": null, "e": 25719, "s": 25665, "text": "Case 1: Accessing protected members in the same class" }, { "code": null, "e": 25778, "s": 25719, "text": "We can access protected members of a class anywhere in it." }, { "code": null, "e": 25787, "s": 25778, "text": "Example:" }, { "code": null, "e": 25792, "s": 25787, "text": "Java" }, { "code": "// Java Program to Illustrate// Accessing Protected Members// in the same class // Main class class Sample { protected int year = 2021; protected void printYear() { System.out.println(\"Its \" + year + \" !!\"); } public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); }}", "e": 26182, "s": 25792, "text": null }, { "code": null, "e": 26199, "s": 26182, "text": "2021\nIts 2021 !!" }, { "code": null, "e": 26273, "s": 26199, "text": "Case 2: Accessing protected members in other classes of the same package " }, { "code": null, "e": 26370, "s": 26273, "text": "We can access protected members of a class in another class that is present in the same package." }, { "code": null, "e": 26375, "s": 26370, "text": "Java" }, { "code": "// Java Program to Illustrate Accessing// Protected Members// In Other Class of Same Package // Class 1class Sample { protected int year = 2021; protected void printYear() { System.out.println(\"Its \"+year+\" !!\"); }} // Class 2public class Test { // Main driver method public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); }}", "e": 26819, "s": 26375, "text": null }, { "code": null, "e": 26836, "s": 26819, "text": "2021\nIts 2021 !!" }, { "code": null, "e": 26920, "s": 26836, "text": "Case 3: Accessing protected members of a class in its subclass in the same package " }, { "code": null, "e": 27020, "s": 26920, "text": "We can access protected members of a class in its subclass if both are present in the same package." }, { "code": null, "e": 27029, "s": 27020, "text": "Example " }, { "code": null, "e": 27034, "s": 27029, "text": "Java" }, { "code": "// Java Program to Illustrate// Accessing Protected Members// of a class in its subclass// in the same package // Class 1class Sample { static protected String title = \"geekforgeeks\"; protected int year = 2021; protected void printYear() { System.out.println(\"Its \"+year+\" !!\"); }} // Class 2public class Test extends Sample { public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); System.out.println(Sample.title); }}", "e": 27575, "s": 27034, "text": null }, { "code": null, "e": 27605, "s": 27575, "text": "2021\nIts 2021 !!\ngeekforgeeks" }, { "code": null, "e": 27682, "s": 27605, "text": "Case 4: Accessing protected members in another class in a different package " }, { "code": null, "e": 27799, "s": 27682, "text": "We cannot access the protected members of a class in a class (non-subclass) that is present in a different package. " }, { "code": null, "e": 27821, "s": 27799, "text": "Example 1: Package 1 " }, { "code": null, "e": 27826, "s": 27821, "text": "Java" }, { "code": "// Java Program to Illustrate// Accessing Protected Members// In Another Class in a// Different Package // Package 1package package1; // Main classpublic class Sample { static protected String title = \"geeksforgeeks\"; protected int year = 2021; // Protected method protected void printYear() { System.out.println(\"Its \"+year+\" !!\"); }}", "e": 28190, "s": 27826, "text": null }, { "code": null, "e": 28213, "s": 28190, "text": " Example 2: Package 2 " }, { "code": null, "e": 28218, "s": 28213, "text": "Java" }, { "code": "// Java Program to Illustrate// Accessing Protected Members// In Another Class in a// Different Package // Package 1package package2;// Importing above packageimport package1.Sample; // Main classpublic class Test { // Main driver method public static void main(String[] args) { Sample sample = new Sample(); System.out.println(sample.year); sample.printYear(); System.out.println(Sample.title); }}", "e": 28664, "s": 28218, "text": null }, { "code": null, "e": 28675, "s": 28664, "text": " Output: " }, { "code": null, "e": 29059, "s": 28675, "text": "error: year has protected access in Sample\n System.out.println(sample.year);\n ^\nerror: printYear() has protected access in Sample\n sample.printYear();\n ^\nerror: title has protected access in Sample\n System.out.println(Sample.title);\n ^" }, { "code": null, "e": 29310, "s": 29059, "text": "It will give a compile-time error. In the following example, we will create two classes. Sample class in package1 and Test class in package2 and try to access protected members of Sample class in Test class. It is justified in the above two examples." }, { "code": null, "e": 29382, "s": 29310, "text": "Case 5: Accessing protected members in sub-class in a different package" }, { "code": null, "e": 29615, "s": 29382, "text": "We can access protected members of a class in its subclass present in a different package. In the following example, we will create two classes. Sample class in package1 and Child class in package2. Child class extends Sample class." }, { "code": null, "e": 29628, "s": 29615, "text": "Example 1.1 " }, { "code": null, "e": 29633, "s": 29628, "text": "Java" }, { "code": "// Java Program to Illustrate Accessing Protected// Members in sub-class in a different package package package1; // Classpublic class Sample { // Protected attributes static protected String title = \"geeksforgeeks\"; protected int year = 2021; protected void printYear() { System.out.println(\"Its \" + year + \" !!\"); }}", "e": 29978, "s": 29633, "text": null }, { "code": null, "e": 29992, "s": 29978, "text": " Example 1.2 " }, { "code": null, "e": 29997, "s": 29992, "text": "Java" }, { "code": "// Java Program to Illustrate Accessing Protected// Members in Sub-class in a different Packagepackage package2;// Importing class from above packageimport package1.Sample; // Main classpublic class Child extends Sample { // Method 1 void helper() { System.out.println(year); printYear(); System.out.println(Sample.title); } // Method 2 // Main driver method public static void main(String[] args) { // Creating child class instance inside main() Child child = new Child(); child.helper(); }}", "e": 30562, "s": 29997, "text": null }, { "code": null, "e": 30570, "s": 30562, "text": "Output " }, { "code": null, "e": 30601, "s": 30570, "text": "2021\nIts 2021 !!\ngeeksforgeeks" }, { "code": null, "e": 31043, "s": 30601, "text": "Note: From the above output it can be perceived we have successfully accessed the protected members directly as these are inherited by the Child class and can be accessed without using any reference. The protected members are inherited by the child classes and can access them as its own members. But we can’t access these members using the reference of the parent class. We can access protected members only by using child class reference. " }, { "code": null, "e": 31054, "s": 31043, "text": "Example 2 " }, { "code": null, "e": 31059, "s": 31054, "text": "Java" }, { "code": "// Java Program to Illustrate Compile-time Error Thrown// When we are Trying to Access Protected Members// Using Parent Class Reference // Importing packagespackage package2;import package1.Sample; // Importing class extending to Parent classpublic class Child extends Sample { // Method 1 void helper() { // Creating instance of Child class inside main() Child myself = new Child(); // As Child is sub-class of Sample, we can access // the static variable here System.out.println(Sample.title); // This will compile fine as we are accessing year // using child class reference variable System.out.println(year); System.out.println(myself.year); // This will compile fine as we are accessing // printYear() method using child class reference // variable printYear(); myself.printYear(); // Creating parent class object Sample sample = new Sample(); // Parent class reference holding child class object Sample child = new Child(); // Note: Below lines of code won't compile as we are // trying to access protected members of parent // class using Parent's class reference which is // present in other package // Errors will be thrown System.out.println(sample.year); sample.printYear(); child.printYear(); } // Method 2 // Main driver method public static void main(String[] args) { // Creating child class instance inside main() Child child = new Child(); // Calling the above method 1 of child class child.helper(); }}", "e": 32726, "s": 31059, "text": null }, { "code": null, "e": 32734, "s": 32726, "text": "Output " }, { "code": null, "e": 33041, "s": 32734, "text": "error: year has protected access in Sample\n System.out.println(sample.year); \n ^\nerror: printYear() has protected access in Sample\n sample.printYear(); \n ^\nerror: printYear() has protected access in Sample\n child.printYear();\n ^" }, { "code": null, "e": 33479, "s": 33041, "text": "So the main difference between default access modifiers and the protected modifier is that default members are accessible only in the current package. While protected members can be accessed anywhere in the same package and outside package only in its child class and using the child class’s reference variable only, not on the reference variable of the parent class. We can’t access protected members using the parent class’s reference." }, { "code": null, "e": 33490, "s": 33481, "text": "sweetyty" }, { "code": null, "e": 33506, "s": 33490, "text": "simranarora5sos" }, { "code": null, "e": 33523, "s": 33506, "text": "access modifiers" }, { "code": null, "e": 33538, "s": 33523, "text": "Blogathon-2021" }, { "code": null, "e": 33550, "s": 33538, "text": "java-basics" }, { "code": null, "e": 33560, "s": 33550, "text": "Blogathon" }, { "code": null, "e": 33565, "s": 33560, "text": "Java" }, { "code": null, "e": 33570, "s": 33565, "text": "Java" }, { "code": null, "e": 33668, "s": 33570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33677, "s": 33668, "text": "Comments" }, { "code": null, "e": 33690, "s": 33677, "text": "Old Comments" }, { "code": null, "e": 33731, "s": 33690, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 33769, "s": 33731, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 33804, "s": 33769, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 33861, "s": 33804, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 33906, "s": 33861, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 33921, "s": 33906, "text": "Arrays in Java" }, { "code": null, "e": 33965, "s": 33921, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33987, "s": 33965, "text": "For-each loop in Java" }, { "code": null, "e": 34023, "s": 33987, "text": "Arrays.sort() in Java with examples" } ]
How to use thread.sleep() in android?
Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to use thread.sleep() in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <EditText android:id="@+id/edit_query" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter string" /> <Button android:id="@+id/click" android:layout_marginTop="50dp" style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored" android:layout_width="wrap_content" android:background="#c1c1c1" android:textColor="#FFF" android:layout_height="wrap_content" android:text="Button" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update textview. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText edit_query; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit_query = findViewById(R.id.edit_query); textView = findViewById(R.id.text); findViewById(R.id.click).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runthread(); } }); } private void runthread() { final String s1 = edit_query.getText().toString(); Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText(s1); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, Enter some text in edit text and click on the button, after 5000ms it will update textview. Click here to download the project code
[ { "code": null, "e": 1295, "s": 1062, "text": "Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to use thread.sleep() in android." }, { "code": null, "e": 1424, "s": 1295, "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": 1489, "s": 1424, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2534, "s": 1489, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"100dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/edit_query\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Enter string\" />\n <Button\n android:id=\"@+id/click\"\n android:layout_marginTop=\"50dp\"\n style=\"@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored\"\n android:layout_width=\"wrap_content\"\n android:background=\"#c1c1c1\"\n android:textColor=\"#FFF\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2681, "s": 2534, "text": "In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update textview." }, { "code": null, "e": 2738, "s": 2681, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4099, "s": 2738, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText edit_query;\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n edit_query = findViewById(R.id.edit_query);\n textView = findViewById(R.id.text);\n findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n runthread();\n }\n });\n }\n\n private void runthread() {\n final String s1 = edit_query.getText().toString();\n Handler handler = new Handler();\n handler.post(new Runnable() {\n @Override\n public void run() {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(s1);\n try {\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n });\n }\n });\n }\n}" }, { "code": null, "e": 4446, "s": 4099, "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": 4559, "s": 4446, "text": "In the above result, Enter some text in edit text and click on the button, after 5000ms it will update textview." }, { "code": null, "e": 4599, "s": 4559, "text": "Click here to download the project code" } ]
Angular ng Bootstrap Collapse Component - GeeksforGeeks
06 Jul, 2021 Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article we will know how to use Collapse in angular ng bootstrap. Collapse is used to make a button that will be collapsed by clicking on it. Installation syntax: ng add @ng-bootstrap/ng-bootstrap Approach: First, install the angular ng bootstrap using the above-mentioned command. Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] In app.component.html make a collapse component. Serve the app using ng serve. Example 1: In this example, we are making a basic collapse component. app.component.html <p> <br/> <button type="button" class="btn btn-success" (click)="collapse.toggle()" [attr.aria-expanded]="!gfg" aria-controls="collapseExample"> Click to collapse </button></p> <div #collapse="ngbCollapse" [(ngbCollapse)]="gfg"> <div class="card"> <div class="card-body"> Angular10 ng bootstrap </div> </div></div> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public gfg = false;} Output: Example 2: In this example, we have pre collapsed the component. app.component.html <p> <br/> <button type="button" class="btn btn-success" (click)="collapse.toggle()" [attr.aria-expanded]="!gfg" aria-controls="collapseExample"> Click to collapse </button></p> <div #collapse="ngbCollapse" [(ngbCollapse)]="gfg"> <div class="card"> <div class="card-body"> Angular10 ng bootstrap </div> </div></div> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public gfg = true;} Output: Reference: https://ng-bootstrap.github.io/#/components/collapse/examples Angular-ng-bootstrap AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25293, "s": 25109, "text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 25443, "s": 25293, "text": "In this article we will know how to use Collapse in angular ng bootstrap. Collapse is used to make a button that will be collapsed by clicking on it." }, { "code": null, "e": 25464, "s": 25443, "text": "Installation syntax:" }, { "code": null, "e": 25498, "s": 25464, "text": "ng add @ng-bootstrap/ng-bootstrap" }, { "code": null, "e": 25508, "s": 25498, "text": "Approach:" }, { "code": null, "e": 25583, "s": 25508, "text": "First, install the angular ng bootstrap using the above-mentioned command." }, { "code": null, "e": 25705, "s": 25583, "text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 25788, "s": 25705, "text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 25837, "s": 25788, "text": "In app.component.html make a collapse component." }, { "code": null, "e": 25867, "s": 25837, "text": "Serve the app using ng serve." }, { "code": null, "e": 25939, "s": 25869, "text": "Example 1: In this example, we are making a basic collapse component." }, { "code": null, "e": 25958, "s": 25939, "text": "app.component.html" }, { "code": "<p> <br/> <button type=\"button\" class=\"btn btn-success\" (click)=\"collapse.toggle()\" [attr.aria-expanded]=\"!gfg\" aria-controls=\"collapseExample\"> Click to collapse </button></p> <div #collapse=\"ngbCollapse\" [(ngbCollapse)]=\"gfg\"> <div class=\"card\"> <div class=\"card-body\"> Angular10 ng bootstrap </div> </div></div>", "e": 26330, "s": 25958, "text": null }, { "code": null, "e": 26344, "s": 26330, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 26948, "s": 26344, "text": null }, { "code": null, "e": 26965, "s": 26948, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public gfg = false;}", "e": 27178, "s": 26965, "text": null }, { "code": null, "e": 27186, "s": 27178, "text": "Output:" }, { "code": null, "e": 27251, "s": 27186, "text": "Example 2: In this example, we have pre collapsed the component." }, { "code": null, "e": 27270, "s": 27251, "text": "app.component.html" }, { "code": "<p> <br/> <button type=\"button\" class=\"btn btn-success\" (click)=\"collapse.toggle()\" [attr.aria-expanded]=\"!gfg\" aria-controls=\"collapseExample\"> Click to collapse </button></p> <div #collapse=\"ngbCollapse\" [(ngbCollapse)]=\"gfg\"> <div class=\"card\"> <div class=\"card-body\"> Angular10 ng bootstrap </div> </div></div>", "e": 27639, "s": 27270, "text": null }, { "code": null, "e": 27653, "s": 27639, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 28255, "s": 27653, "text": null }, { "code": null, "e": 28272, "s": 28255, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public gfg = true;}", "e": 28484, "s": 28272, "text": null }, { "code": null, "e": 28492, "s": 28484, "text": "Output:" }, { "code": null, "e": 28565, "s": 28492, "text": "Reference: https://ng-bootstrap.github.io/#/components/collapse/examples" }, { "code": null, "e": 28586, "s": 28565, "text": "Angular-ng-bootstrap" }, { "code": null, "e": 28596, "s": 28586, "text": "AngularJS" }, { "code": null, "e": 28613, "s": 28596, "text": "Web Technologies" }, { "code": null, "e": 28711, "s": 28613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28720, "s": 28711, "text": "Comments" }, { "code": null, "e": 28733, "s": 28720, "text": "Old Comments" }, { "code": null, "e": 28777, "s": 28733, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28841, "s": 28777, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 28894, "s": 28841, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28918, "s": 28894, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28953, "s": 28918, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28995, "s": 28953, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29028, "s": 28995, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29071, "s": 29028, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29133, "s": 29071, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to Accurately Calculate Age on BigQuery | Towards Data Science
In analysing customer data, age is one of the basic and important demographic data fields. Usually, age is not a data point collected from the customer but rather their date of birth. Age is then calculated from this — either the customer’s age from a moment in time or their age today. Unfortunately, there’s no standard way of calculating age on Bigquery and this leads to different ways of deriving a basic concept. With each unique calculation among developers and analysts, there would be discrepancies between results. I introduce different age calculations below and how to accurately calculate it in BigQuery using SQL. In these examples, I’ll be using the same date of birth (mine). The most basic way of calculating age is to use DATE_DIFF function to get the number of years between two dates. However, this function just subtracts the years, regardless if the date of birth has already passed or not, which is entirely inaccurate. WITH data AS (SELECT CAST('1993-04-29' AS DATE) AS date_of_birth)SELECT DATE_DIFF('2020-03-21',date_of_birth, YEAR) AS ageFROM data Result: 27 Instead of using the difference in years, we can use the same function to calculate the difference in days between a date and the date of birth, then dividing this by 365. FLOOR is used to remove the decimal places. This is useful when it comes to quick analyses and when accuracy is less important. SELECT FLOOR(DATE_DIFF('2020-03-21',date_of_birth, DAY)/365) AS ageFROM data Result: 26 This calculation assumes that all years have 365 days. Since this does not take into account leap years, the age will get rounded up a few days before the actual birth date. The number of days when the age is rounded up is the number of leap years that have passed. FLOOR(DATE_DIFF('2020-04-27',date_of_birth, DAY)/365) AS age Result: 27 Replacing 365 with 365.25 in the divisor gives a more accurate result. FLOOR(DATE_DIFF('2020-04-27',date_of_birth, DAY)/365.25) AS age Result: 26 However, the result gets less accurate at certain ages where the leap year has an impact. FLOOR(DATE_DIFF('2011-04-29',date_of_birth, DAY)/365.25) AS age Result: 17 Here, the age is actually being rounded down. The result should have been 18 in this scenario. While the error has minimal effect and this proves to be a better alternative, there could be cases where accuracy is important. In marketing, calculating age incorrectly can have legal implications or just really bad customer experience. In this seemingly complex (not really) calculation, it uses several functions. The first part of the query subtracts the years between the two dates. The second part will subtract 1 year if the date of birth has already passed the other date by comparing just the month and day. DATE_DIFF('2020-03-21',date_of_birth, YEAR)- IF(EXTRACT(MONTH FROM date_of_birth)*100 + EXTRACT(DAY FROM date_of_birth) > EXTRACT(MONTH FROM '2020-03-21')*100 + EXTRACT(DAY FROM '2020-03-21'),1,0) AS age Result: 26 The downside of using this calculation is that it is long and quite a hassle to redo every time you need age calculated (except when you have the query saved somewhere). BigQuery now allows persistent user-defined functions. This makes it easier to reuse the same code and keep it consistent throughout the project. It’s a struggle as someone who has been coding for a few years now that every time age needs to be derived, I would have to use different functions and write a long query just to get an accurate age. Instead, I created a UDF such that I can reference the same code for every analysis I make. CREATE OR REPLACE FUNCTION workspace.age_calculation(as_of_date DATE, date_of_birth DATE) AS (DATE_DIFF(as_of_date,date_of_birth, YEAR) - IF(EXTRACT(MONTH FROM date_of_birth)*100 + EXTRACT(DAY FROM date_of_birth) > EXTRACT(MONTH FROM as_of_date)*100 + EXTRACT(DAY FROM as_of_date),1,0)) In this UDF, there are two inputs — the date of birth and the as of date you want to calculate the age. This gives the user the flexibility of reusing the code and for different use cases. SELECT workspace.age_calculation('2020-03-21','1993-04-29') Result: 26 It’s interesting that there is no standard way of calculating age when this is such an important attribute, whether in analysing or targeting customers. However, using a combination of BigQuery functions gives better alternatives. I hope this helps analysts use a standard and accurate way of calculating age in their data.
[ { "code": null, "e": 334, "s": 47, "text": "In analysing customer data, age is one of the basic and important demographic data fields. Usually, age is not a data point collected from the customer but rather their date of birth. Age is then calculated from this — either the customer’s age from a moment in time or their age today." }, { "code": null, "e": 572, "s": 334, "text": "Unfortunately, there’s no standard way of calculating age on Bigquery and this leads to different ways of deriving a basic concept. With each unique calculation among developers and analysts, there would be discrepancies between results." }, { "code": null, "e": 739, "s": 572, "text": "I introduce different age calculations below and how to accurately calculate it in BigQuery using SQL. In these examples, I’ll be using the same date of birth (mine)." }, { "code": null, "e": 990, "s": 739, "text": "The most basic way of calculating age is to use DATE_DIFF function to get the number of years between two dates. However, this function just subtracts the years, regardless if the date of birth has already passed or not, which is entirely inaccurate." }, { "code": null, "e": 1124, "s": 990, "text": "WITH data AS (SELECT CAST('1993-04-29' AS DATE) AS date_of_birth)SELECT DATE_DIFF('2020-03-21',date_of_birth, YEAR) AS ageFROM data" }, { "code": null, "e": 1135, "s": 1124, "text": "Result: 27" }, { "code": null, "e": 1435, "s": 1135, "text": "Instead of using the difference in years, we can use the same function to calculate the difference in days between a date and the date of birth, then dividing this by 365. FLOOR is used to remove the decimal places. This is useful when it comes to quick analyses and when accuracy is less important." }, { "code": null, "e": 1514, "s": 1435, "text": "SELECT FLOOR(DATE_DIFF('2020-03-21',date_of_birth, DAY)/365) AS ageFROM data" }, { "code": null, "e": 1525, "s": 1514, "text": "Result: 26" }, { "code": null, "e": 1791, "s": 1525, "text": "This calculation assumes that all years have 365 days. Since this does not take into account leap years, the age will get rounded up a few days before the actual birth date. The number of days when the age is rounded up is the number of leap years that have passed." }, { "code": null, "e": 1852, "s": 1791, "text": "FLOOR(DATE_DIFF('2020-04-27',date_of_birth, DAY)/365) AS age" }, { "code": null, "e": 1863, "s": 1852, "text": "Result: 27" }, { "code": null, "e": 1934, "s": 1863, "text": "Replacing 365 with 365.25 in the divisor gives a more accurate result." }, { "code": null, "e": 1998, "s": 1934, "text": "FLOOR(DATE_DIFF('2020-04-27',date_of_birth, DAY)/365.25) AS age" }, { "code": null, "e": 2009, "s": 1998, "text": "Result: 26" }, { "code": null, "e": 2099, "s": 2009, "text": "However, the result gets less accurate at certain ages where the leap year has an impact." }, { "code": null, "e": 2163, "s": 2099, "text": "FLOOR(DATE_DIFF('2011-04-29',date_of_birth, DAY)/365.25) AS age" }, { "code": null, "e": 2174, "s": 2163, "text": "Result: 17" }, { "code": null, "e": 2398, "s": 2174, "text": "Here, the age is actually being rounded down. The result should have been 18 in this scenario. While the error has minimal effect and this proves to be a better alternative, there could be cases where accuracy is important." }, { "code": null, "e": 2787, "s": 2398, "text": "In marketing, calculating age incorrectly can have legal implications or just really bad customer experience. In this seemingly complex (not really) calculation, it uses several functions. The first part of the query subtracts the years between the two dates. The second part will subtract 1 year if the date of birth has already passed the other date by comparing just the month and day." }, { "code": null, "e": 2991, "s": 2787, "text": "DATE_DIFF('2020-03-21',date_of_birth, YEAR)- IF(EXTRACT(MONTH FROM date_of_birth)*100 + EXTRACT(DAY FROM date_of_birth) > EXTRACT(MONTH FROM '2020-03-21')*100 + EXTRACT(DAY FROM '2020-03-21'),1,0) AS age" }, { "code": null, "e": 3002, "s": 2991, "text": "Result: 26" }, { "code": null, "e": 3172, "s": 3002, "text": "The downside of using this calculation is that it is long and quite a hassle to redo every time you need age calculated (except when you have the query saved somewhere)." }, { "code": null, "e": 3610, "s": 3172, "text": "BigQuery now allows persistent user-defined functions. This makes it easier to reuse the same code and keep it consistent throughout the project. It’s a struggle as someone who has been coding for a few years now that every time age needs to be derived, I would have to use different functions and write a long query just to get an accurate age. Instead, I created a UDF such that I can reference the same code for every analysis I make." }, { "code": null, "e": 3897, "s": 3610, "text": "CREATE OR REPLACE FUNCTION workspace.age_calculation(as_of_date DATE, date_of_birth DATE) AS (DATE_DIFF(as_of_date,date_of_birth, YEAR) - IF(EXTRACT(MONTH FROM date_of_birth)*100 + EXTRACT(DAY FROM date_of_birth) > EXTRACT(MONTH FROM as_of_date)*100 + EXTRACT(DAY FROM as_of_date),1,0))" }, { "code": null, "e": 4086, "s": 3897, "text": "In this UDF, there are two inputs — the date of birth and the as of date you want to calculate the age. This gives the user the flexibility of reusing the code and for different use cases." }, { "code": null, "e": 4146, "s": 4086, "text": "SELECT workspace.age_calculation('2020-03-21','1993-04-29')" }, { "code": null, "e": 4157, "s": 4146, "text": "Result: 26" } ]
HTTP headers | Content-Type - GeeksforGeeks
29 Jul, 2021 The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client. The browser gets to know about the type of content it has to load on the machine. Every time its byte stream of the file that browsers receive, by the Content-type header, the browser will do something known as MIME sniffing i.e. it will inspect the stream it is receiving and then loads the data accordingly. Syntax: Content-Type: text/html; charset=UTF-8 Content-Type: multipart/form-data; boundary=something Directives: There are three directives in the HTTP headers Content-type. media type: It holds the MIME (Multipurpose Internet Mail Extensions) type of the data. charset: It holds the character encoding standard. Charset is the encoding standard in which the data will be received by the browsers. boundary: The boundary directive is required when there is multipart entities. Boundary is for multipart entities consisting of 70 characters from a set of characters known to be very robust through email gateways, and with no white space. Example: This example display how the images are read by browser with and without setting the Content-type header. <?php header('Content-type: image/jpeg');//with header Content type echo file_get_contents("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png"); ?> Output : Now without using Content-type header we will get the content of the image in bytes, So it is not of any use to us. <?php // Without headerecho file_get_contents("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png");?> Output: ?PNG IHDRX??'?iCCPsRGB IEC61966-2.1(?u??+DQ??3????????????63??P????H?U????l??RDJV???9oF? $sn????{N???pZ??^?d?Z(p?E?]??h??QEW?f??T??{, f???????????z?aE??????y???6%]>vkrA?;S?????d??M? ¡?6???`%?????&???Q-Z?j????BSZo?a???}N ?._u {??#??N?g?{-bKGD??????? pHYs.#.#x??vtIME?4_?X IDATx??w?U??????MB$??$@@? 2t?"EDa???"? C?*C????Hq?ja??w ????????L{??}?}??w?;??{???{.4, ???j??? q10??_??h2]`P??:^?5??@?W?=????????XY??? w.??9??`z?1?!V??B????XM~^?|?1?qm???(?h??C?OV?js{e?+ L?b?{%?@`?+:sQ?@? Here, it is clearly visible that by applying the Content-type header information tells the browser, the type of response it is getting from the server. All possible values of HTTP Content-type header: Supported Browsers: The browsers compatible with HTTP headers Content-type are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTTP-headers Picked HTML Web Technologies HTML 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 ? REST API (Introduction) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24836, "s": 24808, "text": "\n29 Jul, 2021" }, { "code": null, "e": 25084, "s": 24836, "text": "The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc." }, { "code": null, "e": 25467, "s": 25084, "text": "In response, it tells about the type of returned content, to the client. The browser gets to know about the type of content it has to load on the machine. Every time its byte stream of the file that browsers receive, by the Content-type header, the browser will do something known as MIME sniffing i.e. it will inspect the stream it is receiving and then loads the data accordingly." }, { "code": null, "e": 25475, "s": 25467, "text": "Syntax:" }, { "code": null, "e": 25569, "s": 25475, "text": "Content-Type: text/html; charset=UTF-8\nContent-Type: multipart/form-data; boundary=something\n" }, { "code": null, "e": 25642, "s": 25569, "text": "Directives: There are three directives in the HTTP headers Content-type." }, { "code": null, "e": 25730, "s": 25642, "text": "media type: It holds the MIME (Multipurpose Internet Mail Extensions) type of the data." }, { "code": null, "e": 25866, "s": 25730, "text": "charset: It holds the character encoding standard. Charset is the encoding standard in which the data will be received by the browsers." }, { "code": null, "e": 26106, "s": 25866, "text": "boundary: The boundary directive is required when there is multipart entities. Boundary is for multipart entities consisting of 70 characters from a set of characters known to be very robust through email gateways, and with no white space." }, { "code": null, "e": 26221, "s": 26106, "text": "Example: This example display how the images are read by browser with and without setting the Content-type header." }, { "code": "<?php header('Content-type: image/jpeg');//with header Content type echo file_get_contents(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\"); ?>", "e": 26392, "s": 26221, "text": null }, { "code": null, "e": 26401, "s": 26392, "text": "Output :" }, { "code": null, "e": 26517, "s": 26401, "text": "Now without using Content-type header we will get the content of the image in bytes, So it is not of any use to us." }, { "code": "<?php // Without headerecho file_get_contents(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\");?>", "e": 26641, "s": 26517, "text": null }, { "code": null, "e": 26649, "s": 26641, "text": "Output:" }, { "code": null, "e": 27130, "s": 26649, "text": "?PNG IHDRX??'?iCCPsRGB IEC61966-2.1(?u??+DQ??3????????????63??P????H?U????l??RDJV???9oF?\n$sn????{N???pZ??^?d?Z(p?E?]??h??QEW?f??T??{, f???????????z?aE??????y???6%]>vkrA?;S?????d??M?\n¡?6???`%?????&???Q-Z?j????BSZo?a???}N ?._u {??#??N?g?{-bKGD??????? pHYs.#.#x??vtIME?4_?X \nIDATx??w?U??????MB$??$@@? 2t?\"EDa???\"? C?*C????Hq?ja??w ????????L{??}?}??w?;??{???{.4, ???j???\nq10??_??h2]`P??:^?5??@?W?=????????XY??? w.??9??`z?1?!V??B????XM~^?|?1?qm???(?h??C?OV?js{e?+ \nL?b?{%?@`?+:sQ?@?" }, { "code": null, "e": 27282, "s": 27130, "text": "Here, it is clearly visible that by applying the Content-type header information tells the browser, the type of response it is getting from the server." }, { "code": null, "e": 27331, "s": 27282, "text": "All possible values of HTTP Content-type header:" }, { "code": null, "e": 27424, "s": 27331, "text": "Supported Browsers: The browsers compatible with HTTP headers Content-type are listed below:" }, { "code": null, "e": 27438, "s": 27424, "text": "Google Chrome" }, { "code": null, "e": 27456, "s": 27438, "text": "Internet Explorer" }, { "code": null, "e": 27464, "s": 27456, "text": "Firefox" }, { "code": null, "e": 27471, "s": 27464, "text": "Safari" }, { "code": null, "e": 27477, "s": 27471, "text": "Opera" }, { "code": null, "e": 27671, "s": 27477, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 27808, "s": 27671, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27821, "s": 27808, "text": "HTTP-headers" }, { "code": null, "e": 27828, "s": 27821, "text": "Picked" }, { "code": null, "e": 27833, "s": 27828, "text": "HTML" }, { "code": null, "e": 27850, "s": 27833, "text": "Web Technologies" }, { "code": null, "e": 27855, "s": 27850, "text": "HTML" }, { "code": null, "e": 27953, "s": 27855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28003, "s": 27953, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28027, "s": 28003, "text": "REST API (Introduction)" }, { "code": null, "e": 28091, "s": 28027, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28128, "s": 28091, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28189, "s": 28128, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28231, "s": 28189, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28264, "s": 28231, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28307, "s": 28264, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28352, "s": 28307, "text": "Convert a string to an integer in JavaScript" } ]
3 Techniques to Effortlessly Import and Execute Python Modules | by Khuyen Tran | Towards Data Science
As a data scientist, you most likely want to share the helpful modules you created with your teammates or other users. Although your module might be useful, others will not use it if it takes them a lot of effort to access the useful functions in your module. Thus, you want to make it easy for users to use your module. The code to import and run your module should be short. In this article, I will show you 3 ways to make it easy to import and execute your Python modules. Imagine we have a file called utils.py that contains all important functions and classes In another script, we want to import everything from utils.py except the variablea using from utils import *. How can we do that? This could easily be done by adding__all__ = [“add_two”, “multiply_by_two”] . Functions, classes, and packages specified in __all__ will be imported when using import * . Now try to use import * in another script 56Traceback (most recent call last): File "main.py", line 6, in <module> print(a)NameError: name 'a' is not defined Cool! The error shows us that only add_two and multiply_by_two from utils.py are imported while ais not imported. Imagine what the structure of the files in our directory looks like below: .├── data_modules│ ├── load_data.py│ └── process_data.py└── main.py load_data.py looks like this: and process_data.py looks like this: To use classes from 2 different files, we need to import each class from each file. This method is fine, but it is redundant to use 2 import statements. Is there a way that we can turn two import statements into one import statement like below? This can be easily solved with __init__.py file. Insert __init__.py file under thedata_modules directory: touch data_modules/__init__.py Then insert the import statements mentioned earlier to the__init__.py file: We use one . here because load_data.py is in the same directory as __init__.py . Now let’s try to import DataLoader and DataProcessor from data_modules Loading data from data/Processing data1 Nice! It works! Our directory looks like this: .└── data_modules ├── __init__.py ├── load_data.py ├── main.py └── process_data.py Instead of running $ python data_modules/main.py we might want to make it simpler for our users or teammates to run the code main.py file by simply running the parent directory: $ python data_modules This is better than runningpython data_modules/main.py because it is shorter, and users don’t need to know what files are in data_modules . How can we do that? This is when __main__.py comes in handy. Simply change the script you want to run when running the top-level directory to __main__.py. In our example, main.py will become __main__.py . # Rename main.py to __main__.py$ mv data_modules/main.py data_modules/__main__.py Our new directory will look like this .└── data_modules ├── __init__.py ├── load_data.py ├── __main__.py └── process_data.py Now run $ python data_modulesLoading data from data/Processing data1 And it works like a charm! Congratulations! You have just learned how to make it easier for you and those who use your package by: Controlling what to import when using import * Shortening your import statements Running the top-level directory as the main script I hope these tricks will make your Python package more user-friendly. Your teammates and users will be happy to use your package if it is easy for them to access your useful modules. The source code of this article could be found here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Beazley, D. M., & Jones, B. K. (2014). Python cookbook. Beijing ; Cambridge ; Farnham ; Köln ; Sebastopol ; Tokyo: O’Reilly.
[ { "code": null, "e": 432, "s": 172, "text": "As a data scientist, you most likely want to share the helpful modules you created with your teammates or other users. Although your module might be useful, others will not use it if it takes them a lot of effort to access the useful functions in your module." }, { "code": null, "e": 648, "s": 432, "text": "Thus, you want to make it easy for users to use your module. The code to import and run your module should be short. In this article, I will show you 3 ways to make it easy to import and execute your Python modules." }, { "code": null, "e": 737, "s": 648, "text": "Imagine we have a file called utils.py that contains all important functions and classes" }, { "code": null, "e": 867, "s": 737, "text": "In another script, we want to import everything from utils.py except the variablea using from utils import *. How can we do that?" }, { "code": null, "e": 1038, "s": 867, "text": "This could easily be done by adding__all__ = [“add_two”, “multiply_by_two”] . Functions, classes, and packages specified in __all__ will be imported when using import * ." }, { "code": null, "e": 1080, "s": 1038, "text": "Now try to use import * in another script" }, { "code": null, "e": 1200, "s": 1080, "text": "56Traceback (most recent call last): File \"main.py\", line 6, in <module> print(a)NameError: name 'a' is not defined" }, { "code": null, "e": 1314, "s": 1200, "text": "Cool! The error shows us that only add_two and multiply_by_two from utils.py are imported while ais not imported." }, { "code": null, "e": 1389, "s": 1314, "text": "Imagine what the structure of the files in our directory looks like below:" }, { "code": null, "e": 1461, "s": 1389, "text": ".├── data_modules│ ├── load_data.py│ └── process_data.py└── main.py" }, { "code": null, "e": 1491, "s": 1461, "text": "load_data.py looks like this:" }, { "code": null, "e": 1528, "s": 1491, "text": "and process_data.py looks like this:" }, { "code": null, "e": 1612, "s": 1528, "text": "To use classes from 2 different files, we need to import each class from each file." }, { "code": null, "e": 1773, "s": 1612, "text": "This method is fine, but it is redundant to use 2 import statements. Is there a way that we can turn two import statements into one import statement like below?" }, { "code": null, "e": 1879, "s": 1773, "text": "This can be easily solved with __init__.py file. Insert __init__.py file under thedata_modules directory:" }, { "code": null, "e": 1910, "s": 1879, "text": "touch data_modules/__init__.py" }, { "code": null, "e": 1986, "s": 1910, "text": "Then insert the import statements mentioned earlier to the__init__.py file:" }, { "code": null, "e": 2067, "s": 1986, "text": "We use one . here because load_data.py is in the same directory as __init__.py ." }, { "code": null, "e": 2138, "s": 2067, "text": "Now let’s try to import DataLoader and DataProcessor from data_modules" }, { "code": null, "e": 2178, "s": 2138, "text": "Loading data from data/Processing data1" }, { "code": null, "e": 2194, "s": 2178, "text": "Nice! It works!" }, { "code": null, "e": 2225, "s": 2194, "text": "Our directory looks like this:" }, { "code": null, "e": 2320, "s": 2225, "text": ".└── data_modules ├── __init__.py ├── load_data.py ├── main.py └── process_data.py" }, { "code": null, "e": 2339, "s": 2320, "text": "Instead of running" }, { "code": null, "e": 2369, "s": 2339, "text": "$ python data_modules/main.py" }, { "code": null, "e": 2498, "s": 2369, "text": "we might want to make it simpler for our users or teammates to run the code main.py file by simply running the parent directory:" }, { "code": null, "e": 2520, "s": 2498, "text": "$ python data_modules" }, { "code": null, "e": 2660, "s": 2520, "text": "This is better than runningpython data_modules/main.py because it is shorter, and users don’t need to know what files are in data_modules ." }, { "code": null, "e": 2680, "s": 2660, "text": "How can we do that?" }, { "code": null, "e": 2865, "s": 2680, "text": "This is when __main__.py comes in handy. Simply change the script you want to run when running the top-level directory to __main__.py. In our example, main.py will become __main__.py ." }, { "code": null, "e": 2947, "s": 2865, "text": "# Rename main.py to __main__.py$ mv data_modules/main.py data_modules/__main__.py" }, { "code": null, "e": 2985, "s": 2947, "text": "Our new directory will look like this" }, { "code": null, "e": 3084, "s": 2985, "text": ".└── data_modules ├── __init__.py ├── load_data.py ├── __main__.py └── process_data.py" }, { "code": null, "e": 3092, "s": 3084, "text": "Now run" }, { "code": null, "e": 3153, "s": 3092, "text": "$ python data_modulesLoading data from data/Processing data1" }, { "code": null, "e": 3180, "s": 3153, "text": "And it works like a charm!" }, { "code": null, "e": 3284, "s": 3180, "text": "Congratulations! You have just learned how to make it easier for you and those who use your package by:" }, { "code": null, "e": 3331, "s": 3284, "text": "Controlling what to import when using import *" }, { "code": null, "e": 3365, "s": 3331, "text": "Shortening your import statements" }, { "code": null, "e": 3416, "s": 3365, "text": "Running the top-level directory as the main script" }, { "code": null, "e": 3599, "s": 3416, "text": "I hope these tricks will make your Python package more user-friendly. Your teammates and users will be happy to use your package if it is easy for them to access your useful modules." }, { "code": null, "e": 3652, "s": 3599, "text": "The source code of this article could be found here:" }, { "code": null, "e": 3663, "s": 3652, "text": "github.com" }, { "code": null, "e": 3823, "s": 3663, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." }, { "code": null, "e": 3999, "s": 3823, "text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:" }, { "code": null, "e": 4022, "s": 3999, "text": "towardsdatascience.com" }, { "code": null, "e": 4045, "s": 4022, "text": "towardsdatascience.com" }, { "code": null, "e": 4068, "s": 4045, "text": "towardsdatascience.com" }, { "code": null, "e": 4091, "s": 4068, "text": "towardsdatascience.com" } ]
Can we overload the main method in Java?
Yes, we can overload the main method in Java, but When we execute the class JVM starts execution with public static void main(String[] args) method. Live Demo public class Sample{ public static void main(){ System.out.println("This is the overloaded main method"); } public static void main(String args[]){ Sample obj = new Sample(); obj.main(); } } This is the overloaded main method
[ { "code": null, "e": 1211, "s": 1062, "text": "Yes, we can overload the main method in Java, but When we execute the class JVM starts execution with public static void main(String[] args) method." }, { "code": null, "e": 1222, "s": 1211, "text": " Live Demo" }, { "code": null, "e": 1443, "s": 1222, "text": "public class Sample{\n public static void main(){\n System.out.println(\"This is the overloaded main method\");\n }\n public static void main(String args[]){\n Sample obj = new Sample();\n obj.main();\n }\n}" }, { "code": null, "e": 1479, "s": 1443, "text": "This is the overloaded main method\n" } ]
GATE | GATE-CS-2003 | Question 31 - GeeksforGeeks
28 Jun, 2021 Let (5, ≤) be a partial order with two minimal elements a and b, and a maximum element c. Let P : S → {True, False} be a predicate defined on S. Suppose that P(a) = True, P(b) = False and P(x) ⇒ P(y) for all x, y ∈ S satisfying x ≤ y, where ⇒ stands for logical implication. Which of the following statements CANNOT be true ?(A) P(x) = True for all x ∈ S such that x ≠ b(B) P(x) = False for all x ∈ S such that x ≠ a and x ≠ c(C) P(x) = False for all x ∈ S such that b ≤ x and x ≠ c(D) P(x) = False for all x ∈ S such that a ≤ x and b ≤ xAnswer: (D)Explanation:‘a’ and ‘b’ are given as minimal elements. No other element in S is of lower order than either a or b.‘c’ is given as maximum element. So, c is of higher order than any other element in S.P(a) = True means all elements ‘x’ which have an edge from element ‘a’ have to be true.Since there is an edge from ‘a’, we have to satisfy formula P(a) => P(x), which can only be done by settingP(x) = True.Elements which have an edge from b can be anything because formula P(b) => P(x) is satisfied as P(b) = False.(A) This statement is true because making all elements true trivially satisfy formula P(x) => P(y).(B) This statement is true if all elements are connected from b then all elements can be false.(C) This statement is true because b<=x ensures x!=a and for all other elements P(x) can be false without violating the given implication.(D) This statement is false. Since, P(a) = true , for all ‘x’ such that a<=x, P(x) must be true. We do have at least one such 'x', which is 'c' as it is the maximum element. Thus, option (D) is the answer. Please comment below if you find anything wrong in the above post. Quiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | Gate IT 2007 | Question 30 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE MOCK 2017 | Question 19
[ { "code": null, "e": 24466, "s": 24438, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24556, "s": 24466, "text": "Let (5, ≤) be a partial order with two minimal elements a and b, and a maximum element c." }, { "code": null, "e": 24743, "s": 24556, "text": "Let P : S → {True, False} be a predicate defined on S.\nSuppose that P(a) = True, P(b) = False and \nP(x) ⇒ P(y) for all x, y ∈ S satisfying x ≤ y, \nwhere ⇒ stands for logical implication." }, { "code": null, "e": 26141, "s": 24743, "text": "Which of the following statements CANNOT be true ?(A) P(x) = True for all x ∈ S such that x ≠ b(B) P(x) = False for all x ∈ S such that x ≠ a and x ≠ c(C) P(x) = False for all x ∈ S such that b ≤ x and x ≠ c(D) P(x) = False for all x ∈ S such that a ≤ x and b ≤ xAnswer: (D)Explanation:‘a’ and ‘b’ are given as minimal elements. No other element in S is of lower order than either a or b.‘c’ is given as maximum element. So, c is of higher order than any other element in S.P(a) = True means all elements ‘x’ which have an edge from element ‘a’ have to be true.Since there is an edge from ‘a’, we have to satisfy formula P(a) => P(x), which can only be done by settingP(x) = True.Elements which have an edge from b can be anything because formula P(b) => P(x) is satisfied as P(b) = False.(A) This statement is true because making all elements true trivially satisfy formula P(x) => P(y).(B) This statement is true if all elements are connected from b then all elements can be false.(C) This statement is true because b<=x ensures x!=a and for all other elements P(x) can be false without violating the given implication.(D) This statement is false. Since, P(a) = true , for all ‘x’ such that a<=x, P(x) must be true. We do have at least one such 'x', which is 'c' as it is the maximum element. Thus, option (D) is the answer. Please comment below if you find anything wrong in the above post." }, { "code": null, "e": 26163, "s": 26141, "text": "Quiz of this Question" }, { "code": null, "e": 26176, "s": 26163, "text": "GATE-CS-2003" }, { "code": null, "e": 26194, "s": 26176, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 26199, "s": 26194, "text": "GATE" }, { "code": null, "e": 26297, "s": 26199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26331, "s": 26297, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26365, "s": 26331, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26407, "s": 26365, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26441, "s": 26407, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26474, "s": 26441, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26508, "s": 26474, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 26550, "s": 26508, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 26584, "s": 26550, "text": "GATE | Gate IT 2007 | Question 30" }, { "code": null, "e": 26626, "s": 26584, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
How to capitalize the first letter of each word in a string using JavaScript?
At first, you need to split() the string on the basis of space and extract the first character using charAt(). Use toUpperCase() for the extracted character. function capitalizeTheFirstLetterOfEachWord(words) { var separateWord = words.toLowerCase().split(' '); for (var i = 0; i < separateWord.length; i++) { separateWord[i] = separateWord[i].charAt(0).toUpperCase() + separateWord[i].substring(1); } return separateWord.join(' '); } console.log(capitalizeTheFirstLetterOfEachWord("my name is john")); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo43.js. This will produce the following output with first letter capitalize − PS C:\Users\Amit\JavaScript-code> node demo43.js My Name Is John
[ { "code": null, "e": 1220, "s": 1062, "text": "At first, you need to split() the string on the basis of space and extract the first character using\ncharAt(). Use toUpperCase() for the extracted character." }, { "code": null, "e": 1589, "s": 1220, "text": "function capitalizeTheFirstLetterOfEachWord(words) {\n var separateWord = words.toLowerCase().split(' ');\n for (var i = 0; i < separateWord.length; i++) {\n separateWord[i] = separateWord[i].charAt(0).toUpperCase() +\n separateWord[i].substring(1);\n }\n return separateWord.join(' ');\n}\nconsole.log(capitalizeTheFirstLetterOfEachWord(\"my name is john\"));" }, { "code": null, "e": 1655, "s": 1589, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1673, "s": 1655, "text": "node fileName.js." }, { "code": null, "e": 1706, "s": 1673, "text": "Here, my file name is demo43.js." }, { "code": null, "e": 1776, "s": 1706, "text": "This will produce the following output with first letter capitalize −" }, { "code": null, "e": 1841, "s": 1776, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo43.js\nMy Name Is John" } ]
An Intuitive Guide to kNN with Implementation | by Dr. Saptarsi Goswami | Towards Data Science
kNN is one of the simplest algorithms of classification and, as a result, remains one of the ‘darlings’ of the community. There have been quite a few surveys on popular machine learning algorithms and very rarely, kNN could be put outside of the top 10. You can check our video here and our code here on KNN. Let’s first of all, look at the intuition. In any class, when there are students of multiple disciplines attending, there is a tendency of students of the same discipline to sit together. kNN leverages this idea. Let’s, start with an example, to understand how it works. There are three types(classes) of birds. The task is to find the type(class) of the new bird labeled by the question mark. We look at it’s three nearest neighbors (Encircled), observe that the majority of the neighbors are ducks (2 out of 3), and conclude this unlabeled observation is a duck. In this example, we have looked at three nearest neighbors, so the value of k has been taken as 3. Birds of the same feather flock together Hence, there are two design decisions to be considered: How many neighbors are to be considered? if we keep a small value it will identify local patterns, may pick noise also in some cases. A very high value of k, it will look at the global pattern. In the worst case, it will behave like the prior probability of the naive Bayes. Irrespective of where the data lies, it will assign it to the majority class. Which distance measure is to be used? It can be Euclidian, Manhattan, Hamming Distance, Inverse of Cosine Similarity, etc. Interested readers can look at reference 1, a book only on distance measures. Implementation: The following code is enough to import and instantiate the classifier. from sklearn.neighbors import KNeighborsClassifier#Initalize the classifierknn = KNeighborsClassifier(n_neighbors=15) What are the important parameters of kNN in scikit? n_neighbors: Same meaning as ‘k’, default value is 5 weights: The possible values are uniform and distance. By default, it’s uniform, where all neighbors have an equal weightage of votes when you use distance, which means nearer neighbor will have more weightage, compared to further ones. algorithm: The best option is to use ‘auto’, in this step the distance matrix is computed, which is the most computationally expensive part of kNN. p: if p =2 then it is Euclidian Distance, if 1 then Manhattan, this is applicable when the metric is Minkowski. The equation is given for two p dimensional vectors x1 and x2. metric: By default it is Minkowski, there are a lot of options based on the data type of the two vectors, some of them are listed in the below table. There is also an option to create your own distance metric, but that’s a separate story. How to determine the optimal value of ‘k’? The easiest solution is to take different values of ‘k’ and run the algorithm, check the test set accuracy, where we see a saturation, we can stop there. # Initialize an array with diffrent choices of 'k'nc=np.arange(1,100,2)#Creating an array to store the accuracy valuesacc=np.empty(50)i=0for k in np.nditer(nc): #Initializing kNN with diffrent values of K knn = KNeighborsClassifier(n_neighbors=int(k)) knn.fit(x_train, y_train) #Finding the testing set accuracy acc[i]== knn.score(x_test, y_test) i = i + 1 Next, is plotting the accuracy with different values of ‘k’ x=pd.Series(acc,index=nc)x.plot()# Add title and axis namesplt.title('Neighbor vs Accuracy')plt.xlabel('Count of Neighbor')plt.ylabel('Accuracy')plt.show() We can stop at a small value of ‘k’ here maybe around 6,7 as per figure 3. Why do the distance-based algorithms need scaling? Again let’s take an example. Let’s say, we have data from three customers and we have two attributes age and salary. So three vectors and each vector is two dimensional. We have to determine who is the nearest neighbor of C1. If we do the calculation, we will realize that both the distance comes to 1, hence they are equidistance. However, the change of 1 Rs in Salary and change of 1 Rs in Age is not equivalent, and as the range of salary will be quite high compared to Age, in the Euclidian Distance calculation, it will suffocate or dominate Age. One standard technique to bring them to the same range is called normalization or min-max scaling, given by equation 2 A fictitious illustration with age is enclosed below So, all values are mapped between 0 to 1, with the minimum value being mapped to 0 and the maximum value is mapped to 1. # Impoting minmaxscalerfrom sklearn.preprocessing import MinMaxScaler #Initilizationscaler = MinMaxScaler(feature_range=(0, 1)) #Transforming the valuex_scaled = scaler.fit_transform(x) Critical Remarks: kNN is a very simple algorithm and does not assume anything about the data distribution, hence called as non-parametric. Determining ‘k’ is not easy. As the number of dimensions increases many distance measures do not work well. Finally, the computation of the neighborhood matrix is very expensive. It can be trivially extended to regression, where the value of the target variable will be an average of its k nearest neighbors. It is also tolerant to change in input data, as it starts it’s computation, only when asked to classify. It is often called as Lazy learner. Reference: [1] Deza MM, Deza E. Encyclopedia of distances. In Encyclopedia of distances 2009 (pp. 1–583). Springer, Berlin, Heidelberg.
[ { "code": null, "e": 480, "s": 171, "text": "kNN is one of the simplest algorithms of classification and, as a result, remains one of the ‘darlings’ of the community. There have been quite a few surveys on popular machine learning algorithms and very rarely, kNN could be put outside of the top 10. You can check our video here and our code here on KNN." }, { "code": null, "e": 693, "s": 480, "text": "Let’s first of all, look at the intuition. In any class, when there are students of multiple disciplines attending, there is a tendency of students of the same discipline to sit together. kNN leverages this idea." }, { "code": null, "e": 751, "s": 693, "text": "Let’s, start with an example, to understand how it works." }, { "code": null, "e": 874, "s": 751, "text": "There are three types(classes) of birds. The task is to find the type(class) of the new bird labeled by the question mark." }, { "code": null, "e": 1144, "s": 874, "text": "We look at it’s three nearest neighbors (Encircled), observe that the majority of the neighbors are ducks (2 out of 3), and conclude this unlabeled observation is a duck. In this example, we have looked at three nearest neighbors, so the value of k has been taken as 3." }, { "code": null, "e": 1185, "s": 1144, "text": "Birds of the same feather flock together" }, { "code": null, "e": 1241, "s": 1185, "text": "Hence, there are two design decisions to be considered:" }, { "code": null, "e": 1282, "s": 1241, "text": "How many neighbors are to be considered?" }, { "code": null, "e": 1594, "s": 1282, "text": "if we keep a small value it will identify local patterns, may pick noise also in some cases. A very high value of k, it will look at the global pattern. In the worst case, it will behave like the prior probability of the naive Bayes. Irrespective of where the data lies, it will assign it to the majority class." }, { "code": null, "e": 1632, "s": 1594, "text": "Which distance measure is to be used?" }, { "code": null, "e": 1795, "s": 1632, "text": "It can be Euclidian, Manhattan, Hamming Distance, Inverse of Cosine Similarity, etc. Interested readers can look at reference 1, a book only on distance measures." }, { "code": null, "e": 1811, "s": 1795, "text": "Implementation:" }, { "code": null, "e": 1882, "s": 1811, "text": "The following code is enough to import and instantiate the classifier." }, { "code": null, "e": 2000, "s": 1882, "text": "from sklearn.neighbors import KNeighborsClassifier#Initalize the classifierknn = KNeighborsClassifier(n_neighbors=15)" }, { "code": null, "e": 2052, "s": 2000, "text": "What are the important parameters of kNN in scikit?" }, { "code": null, "e": 2105, "s": 2052, "text": "n_neighbors: Same meaning as ‘k’, default value is 5" }, { "code": null, "e": 2342, "s": 2105, "text": "weights: The possible values are uniform and distance. By default, it’s uniform, where all neighbors have an equal weightage of votes when you use distance, which means nearer neighbor will have more weightage, compared to further ones." }, { "code": null, "e": 2490, "s": 2342, "text": "algorithm: The best option is to use ‘auto’, in this step the distance matrix is computed, which is the most computationally expensive part of kNN." }, { "code": null, "e": 2665, "s": 2490, "text": "p: if p =2 then it is Euclidian Distance, if 1 then Manhattan, this is applicable when the metric is Minkowski. The equation is given for two p dimensional vectors x1 and x2." }, { "code": null, "e": 2815, "s": 2665, "text": "metric: By default it is Minkowski, there are a lot of options based on the data type of the two vectors, some of them are listed in the below table." }, { "code": null, "e": 2904, "s": 2815, "text": "There is also an option to create your own distance metric, but that’s a separate story." }, { "code": null, "e": 2947, "s": 2904, "text": "How to determine the optimal value of ‘k’?" }, { "code": null, "e": 3101, "s": 2947, "text": "The easiest solution is to take different values of ‘k’ and run the algorithm, check the test set accuracy, where we see a saturation, we can stop there." }, { "code": null, "e": 3480, "s": 3101, "text": "# Initialize an array with diffrent choices of 'k'nc=np.arange(1,100,2)#Creating an array to store the accuracy valuesacc=np.empty(50)i=0for k in np.nditer(nc): #Initializing kNN with diffrent values of K knn = KNeighborsClassifier(n_neighbors=int(k)) knn.fit(x_train, y_train) #Finding the testing set accuracy acc[i]== knn.score(x_test, y_test) i = i + 1" }, { "code": null, "e": 3540, "s": 3480, "text": "Next, is plotting the accuracy with different values of ‘k’" }, { "code": null, "e": 3696, "s": 3540, "text": "x=pd.Series(acc,index=nc)x.plot()# Add title and axis namesplt.title('Neighbor vs Accuracy')plt.xlabel('Count of Neighbor')plt.ylabel('Accuracy')plt.show()" }, { "code": null, "e": 3771, "s": 3696, "text": "We can stop at a small value of ‘k’ here maybe around 6,7 as per figure 3." }, { "code": null, "e": 3822, "s": 3771, "text": "Why do the distance-based algorithms need scaling?" }, { "code": null, "e": 4048, "s": 3822, "text": "Again let’s take an example. Let’s say, we have data from three customers and we have two attributes age and salary. So three vectors and each vector is two dimensional. We have to determine who is the nearest neighbor of C1." }, { "code": null, "e": 4374, "s": 4048, "text": "If we do the calculation, we will realize that both the distance comes to 1, hence they are equidistance. However, the change of 1 Rs in Salary and change of 1 Rs in Age is not equivalent, and as the range of salary will be quite high compared to Age, in the Euclidian Distance calculation, it will suffocate or dominate Age." }, { "code": null, "e": 4493, "s": 4374, "text": "One standard technique to bring them to the same range is called normalization or min-max scaling, given by equation 2" }, { "code": null, "e": 4546, "s": 4493, "text": "A fictitious illustration with age is enclosed below" }, { "code": null, "e": 4667, "s": 4546, "text": "So, all values are mapped between 0 to 1, with the minimum value being mapped to 0 and the maximum value is mapped to 1." }, { "code": null, "e": 4853, "s": 4667, "text": "# Impoting minmaxscalerfrom sklearn.preprocessing import MinMaxScaler #Initilizationscaler = MinMaxScaler(feature_range=(0, 1)) #Transforming the valuex_scaled = scaler.fit_transform(x)" }, { "code": null, "e": 4871, "s": 4853, "text": "Critical Remarks:" }, { "code": null, "e": 4992, "s": 4871, "text": "kNN is a very simple algorithm and does not assume anything about the data distribution, hence called as non-parametric." }, { "code": null, "e": 5021, "s": 4992, "text": "Determining ‘k’ is not easy." }, { "code": null, "e": 5100, "s": 5021, "text": "As the number of dimensions increases many distance measures do not work well." }, { "code": null, "e": 5171, "s": 5100, "text": "Finally, the computation of the neighborhood matrix is very expensive." }, { "code": null, "e": 5301, "s": 5171, "text": "It can be trivially extended to regression, where the value of the target variable will be an average of its k nearest neighbors." }, { "code": null, "e": 5442, "s": 5301, "text": "It is also tolerant to change in input data, as it starts it’s computation, only when asked to classify. It is often called as Lazy learner." }, { "code": null, "e": 5453, "s": 5442, "text": "Reference:" } ]
CNN & ResNets — a more liberal understanding | by Rrohan.Arrora | Towards Data Science
If you are familiar with fastai and particularly computer vision in fastai, then you know how we create a convolutional neural network. We use to create the network. If you want to learn about the semantics behind create_cnn, please refer to the link shared in the introduction. Now, we have a CNN, and we want to know what is going on in the CNN. What is going on behind the scene is like below: Now, instead of matrix multiplication, in convolutional neural networks, convolution happens. Convolution is also a type of matrix multiplication, but it has some other magnetic properties also. Let us go deep inside the convolutional neural network. A convolutional neural network consists of a kernel. A kernel is another matrix of any size like 2X2, 3X3, 4X4 or 1X1. This matrix has some numbers which basically defines a particular feature. By, a particular feature, I mean, the kernel in the first layer may filter out top edges in the input matrix(matrix of pixels representing an image), the kernel in the second layer may filter out left corners, the kernel in the third layer may filter out diagonal patterns and so on. Now, when the input matrix is multiplied with the kernel, the output that comes out is known as a Channel. Now, there can be as many layers as we want. ResNet34 has 34 layers of the above operation. So, in gist, we could say like we have many layers of matrix multiplications and in each layer of matrix multiplication, we multiply a kernel with the input matrix of pixels, and we get a channel in the output. In novices language, think of any image and put the light of torch over the image. Pass the light through small parts of the image starting from top-left to bottom-right in parts. That small lighten up portion of the image is actually the kernel and the process of running torchlight over the whole image is kind of convolution. Let us understand the above operation diagrammatically. The number of equations formed is below: Thus the input image is reduced to a smaller matrix known as a channel representing a certain feature. Now, we may understand it in the traditional neural network way like below: We may perform the operations in the conventional neural network way, but it takes a lot of memory and time. Instead, we perform it the other way as stated above, and it takes a whole of less time and memory. Now, let us consider one more case of a convolutional neural network. What if our input matrix and kernel have the same size? There are two options to deal with such situations: We may convolute the complete input matrix and obtain rank one tensor. Otherwise, we add zero paddings or reflection paddings around the input matrix and then convolute the input matrix-like stated below. Fastai frequently uses reflection padding wherever possible. In other words, a convolution is just a matrix multiplication where two things happen: some of the entries are set to zero all the time same kernel weights are multiplied to compute different channels So when you’ve got multiple things with the same weight, that’s called weight tying. Now, that’s much of the theoretical understanding of the convolutional neural networks. Now, let’s understand the convolutional neural networks from a practical point of view. In reality, we have 3D input images rather than 2D images. Each image has different red, green and blue pixels. So, instead of having a rank two tensor kernel, we have rank three tensor kernel representing different values for red, green and blue. So, instead of doing an element-wise multiplication of 9 things(if we have 2D kernel having nine values), we’re going to do an element-wise multiplication of 27 things (3 by three by 3), and we’re still going to then add them up into a single number. Now, when we are convoluting the image, we don’t want only to find top edges but other things also like detecting repetitions, gradients of colours in the image, etc. TO cover all the different features, we need more and more kernels, and this is actually what happens. In each layer, we process the image using a lot of kernels. Thus, each layer consists of a large number of channels. To avoid our memory going out of control due to a lot of channels, from time to time we create a convolution where we don’t step over every single set of 3x3(considering the size of the kernel), but instead, we skip over two at a time. We would start with a 3x3 centered at (2, 2) and then we’d jump over to (2, 4), (2, 6), (2, 8), and so forth. That’s called a stride two convolution. What that does is, it looks the same, it’s still just a bunch of kernels, but we’re just jumping over two at a time. We’re skipping every other input pixel. So the output from that will be H/2 by W/2. (We may define stride-n convolution) Let’s see the stride-4 convolution. Now, let’s evaluate the MNIST dataset and use our convolutional neural network. I used google colab for a practical purpose. from fastai.vision import * Fastai provides academic datasets, and we can untar and use that. path = untar_data(URLs.MNIST)path.ls() After extracting the data, we have to create the data bunch. So, let us establish that. The first thing you say is what kind of item list do you have. So, in this case, it’s the list of images. Then where are you getting the list of file names from? In this case, we have folders. imagelist = ImageList.from_folder(path); imagelist So inside an item list is an items attribute and the items attribute is the kind of thing that you gave it. It's the thing that it's going to use to create your items. So in this case, the thing you gave it is a list of file names. That's what it got from the folder. imagelist.items When you show images, it usually shows them in RGB. In this case, we want to use a binary color map. defaults.cmap='binary'imagelist[22].show() Once you’ve got an image item list, you then split it into training versus validation. You nearly always want validation. If you don’t, you can use the .no_split method to create an empty validation set. You can't skip it entirely. All this is defined in fastai data block API. splitData = imagelist.split_by_folder(train='training', valid='testing'); splitData So that is always the order. First, create your item list, then decide how to split. In this case, we’re going to do it based on folders. The validation folder for MNIST is called testing , and therefore we mention that in the method also. Now, we want to label our data, and we want to label the data using the folder in which our data is present. labelist = splitData.label_from_folder() So first you create the item list, then you split it, then you label it. x,y = labelist.train[0] or labelist.valid[0]x.show()print(x.shape, y) Now, comes adding transforms. Transformation is the part of data augmentation. There is a very considerable difference between processes that we add for tabular data and transformations that we add for images. Processes are added once on the training data, and the same validations are carried to the validation and testing data.s. Transformations are applied every time we ask for the bunch of images. Since we are doing digit recognition, therefore we do not want to apply a default to the data because it consists of some transformations that we really do not want like flipping the number vertically/horizontally will change the number, zooming the text will change the pixels of image and image will be blurred. Therefore, we will add our transformations, and they are effortless, add random padding and a little amount of cropping. tfms = ([*rand_pad(padding=3, size=28, mode='zeros')], [])(empty array refers to the validaion set transforms)transformedlist = labelist.transform(tfms) Now is the time for the last step, and it is to create the data bunch. Here I am not using image stats for normalization as I am not using a pre-trained model like ResNet34, ResNet56, etc. Also, I will use the batch size of 128. bs = 128data = transformedlist.databunch(bs=bs).normalize()x,y = data.train_ds[0]x.show()print(y) What is most interesting is that the training data set now has data augmentation because we have added transforms. plot_multi is a fast.ai function that will plot the result of calling some function on each of the items. def _plot(i,j,ax): data.train_ds[0][0].show(ax, cmap='gray')plot_multi(_plot, 3, 3, figsize=(7, 7)) xb,yb = data.one_batch()xb.shape,yb.shape data.show_batch(rows=3, figsize=(5,5)) Now, we are done with the data bunch. Now, we will create the learner and will train it through our own CNN. def conv(ni,nf): return nn.Conv2d(ni, nf, kernel_size=3, stride=2, padding=1)model = nn.Sequential( conv(3, 8), # 14 nn.BatchNorm2d(8), nn.ReLU(),conv(8, 16), # 7 nn.BatchNorm2d(16), nn.ReLU(),conv(16, 32), # 4 nn.BatchNorm2d(32), nn.ReLU(),conv(32, 16), # 2 nn.BatchNorm2d(16), nn.ReLU(),conv(16, 10), # 1 nn.BatchNorm2d(10), Flatten() # remove (1,1) grid) Let us understand the above function. We are declaring the kernel size to be 3 * 3. We want to perform the stride-2 convolution. Now, We want to perform the sequential operation, that’s why we have written nn.Sequential. The first layer of the model is conv(3, 8). 3 implies to the number of input channels. Since our image has three input channels, therefore we have declared that number. See the image below. 8 is the total number of channels in the output. This number implies the total number of filters, as discussed in the above section. The number of channels in the output of one layer is input to the next layer. Now, we have mentioned using stride-2 convolution. Therefore, we started with an image size of 28 * 28. In the second layer, it will turn down to 14 * 14, in the next layer to 7 * 7 and then to 4 * 4, then to 2 * 2 and lastly to 1 * 1. The output will be in the form of [128, 10, 1, 1] — each image in the batch of 128 has ten channels of 1 * 1in the output as rank three tensors. We flatten it to rank one tensor. In between the convolution layers, we have added batch normalization and ReLu as a non-linear layer. That’s all ( ͡ᴖ ͜ʖ ͡ᴖ), we have created our convolutional neural network. Now is the time to create the learner as defined in the fastai. learn = Learner(data, model, loss_func = nn.CrossEntropyLoss(), metrics=accuracy)learn.summary() learn.lr_find(end_lr=100)learn.recorder.plot() learn.fit_one_cycle(10, max_lr=0.1) Now, let us understand the ResNet and then I will include that in our model and will see how much the accuracy improves. Let X be out input. As per the ResNet, instead of doing like Y = conv2(conv1(X)), It does like so, Y = X + conv2(conv1(X)) — This thing is called an identity connection or skip connection. ResNet drastically improves the loss function surface. Without ResNets, the loss function has lots of bumps, and with ResNet, it turned down to smooth. We can create ResBock like below: class ResBlock(nn.Module): def __init__(self, nf): super().__init__() self.conv1 = conv_layer(nf,nf) self.conv2 = conv_layer(nf,nf) def forward(self, x): return x + self.conv2(self.conv1(x)) Let us change our model to include the ResNet blocks. Let’s refactor that a little. Rather than saying conv, batch norm, ReLU all the time, fast.ai already has something called conv_layer which lets you create conv, batch norm, ReLU combinations. def conv2(ni,nf): return conv_layer(ni,nf,stride=2)model = nn.Sequential( conv2(1, 8), res_block(8), conv2(8, 16), res_block(16), conv2(16, 32), res_block(32), conv2(32, 16), res_block(16), conv2(16, 10), Flatten())learn = Learner(data, model, loss_func = nn.CrossEntropyLoss(), metrics=accuracy)learn.fit_one_cycle(12, max_lr=0.05) That’s all. I hope you may have understood the logic behind CNN and ResNets.
[ { "code": null, "e": 451, "s": 172, "text": "If you are familiar with fastai and particularly computer vision in fastai, then you know how we create a convolutional neural network. We use to create the network. If you want to learn about the semantics behind create_cnn, please refer to the link shared in the introduction." }, { "code": null, "e": 569, "s": 451, "text": "Now, we have a CNN, and we want to know what is going on in the CNN. What is going on behind the scene is like below:" }, { "code": null, "e": 820, "s": 569, "text": "Now, instead of matrix multiplication, in convolutional neural networks, convolution happens. Convolution is also a type of matrix multiplication, but it has some other magnetic properties also. Let us go deep inside the convolutional neural network." }, { "code": null, "e": 1014, "s": 820, "text": "A convolutional neural network consists of a kernel. A kernel is another matrix of any size like 2X2, 3X3, 4X4 or 1X1. This matrix has some numbers which basically defines a particular feature." }, { "code": null, "e": 1298, "s": 1014, "text": "By, a particular feature, I mean, the kernel in the first layer may filter out top edges in the input matrix(matrix of pixels representing an image), the kernel in the second layer may filter out left corners, the kernel in the third layer may filter out diagonal patterns and so on." }, { "code": null, "e": 1497, "s": 1298, "text": "Now, when the input matrix is multiplied with the kernel, the output that comes out is known as a Channel. Now, there can be as many layers as we want. ResNet34 has 34 layers of the above operation." }, { "code": null, "e": 1708, "s": 1497, "text": "So, in gist, we could say like we have many layers of matrix multiplications and in each layer of matrix multiplication, we multiply a kernel with the input matrix of pixels, and we get a channel in the output." }, { "code": null, "e": 2037, "s": 1708, "text": "In novices language, think of any image and put the light of torch over the image. Pass the light through small parts of the image starting from top-left to bottom-right in parts. That small lighten up portion of the image is actually the kernel and the process of running torchlight over the whole image is kind of convolution." }, { "code": null, "e": 2093, "s": 2037, "text": "Let us understand the above operation diagrammatically." }, { "code": null, "e": 2134, "s": 2093, "text": "The number of equations formed is below:" }, { "code": null, "e": 2237, "s": 2134, "text": "Thus the input image is reduced to a smaller matrix known as a channel representing a certain feature." }, { "code": null, "e": 2313, "s": 2237, "text": "Now, we may understand it in the traditional neural network way like below:" }, { "code": null, "e": 2522, "s": 2313, "text": "We may perform the operations in the conventional neural network way, but it takes a lot of memory and time. Instead, we perform it the other way as stated above, and it takes a whole of less time and memory." }, { "code": null, "e": 2700, "s": 2522, "text": "Now, let us consider one more case of a convolutional neural network. What if our input matrix and kernel have the same size? There are two options to deal with such situations:" }, { "code": null, "e": 2771, "s": 2700, "text": "We may convolute the complete input matrix and obtain rank one tensor." }, { "code": null, "e": 2966, "s": 2771, "text": "Otherwise, we add zero paddings or reflection paddings around the input matrix and then convolute the input matrix-like stated below. Fastai frequently uses reflection padding wherever possible." }, { "code": null, "e": 3053, "s": 2966, "text": "In other words, a convolution is just a matrix multiplication where two things happen:" }, { "code": null, "e": 3102, "s": 3053, "text": "some of the entries are set to zero all the time" }, { "code": null, "e": 3167, "s": 3102, "text": "same kernel weights are multiplied to compute different channels" }, { "code": null, "e": 3252, "s": 3167, "text": "So when you’ve got multiple things with the same weight, that’s called weight tying." }, { "code": null, "e": 3428, "s": 3252, "text": "Now, that’s much of the theoretical understanding of the convolutional neural networks. Now, let’s understand the convolutional neural networks from a practical point of view." }, { "code": null, "e": 3927, "s": 3428, "text": "In reality, we have 3D input images rather than 2D images. Each image has different red, green and blue pixels. So, instead of having a rank two tensor kernel, we have rank three tensor kernel representing different values for red, green and blue. So, instead of doing an element-wise multiplication of 9 things(if we have 2D kernel having nine values), we’re going to do an element-wise multiplication of 27 things (3 by three by 3), and we’re still going to then add them up into a single number." }, { "code": null, "e": 4314, "s": 3927, "text": "Now, when we are convoluting the image, we don’t want only to find top edges but other things also like detecting repetitions, gradients of colours in the image, etc. TO cover all the different features, we need more and more kernels, and this is actually what happens. In each layer, we process the image using a lot of kernels. Thus, each layer consists of a large number of channels." }, { "code": null, "e": 4938, "s": 4314, "text": "To avoid our memory going out of control due to a lot of channels, from time to time we create a convolution where we don’t step over every single set of 3x3(considering the size of the kernel), but instead, we skip over two at a time. We would start with a 3x3 centered at (2, 2) and then we’d jump over to (2, 4), (2, 6), (2, 8), and so forth. That’s called a stride two convolution. What that does is, it looks the same, it’s still just a bunch of kernels, but we’re just jumping over two at a time. We’re skipping every other input pixel. So the output from that will be H/2 by W/2. (We may define stride-n convolution)" }, { "code": null, "e": 4974, "s": 4938, "text": "Let’s see the stride-4 convolution." }, { "code": null, "e": 5099, "s": 4974, "text": "Now, let’s evaluate the MNIST dataset and use our convolutional neural network. I used google colab for a practical purpose." }, { "code": null, "e": 5127, "s": 5099, "text": "from fastai.vision import *" }, { "code": null, "e": 5193, "s": 5127, "text": "Fastai provides academic datasets, and we can untar and use that." }, { "code": null, "e": 5232, "s": 5193, "text": "path = untar_data(URLs.MNIST)path.ls()" }, { "code": null, "e": 5320, "s": 5232, "text": "After extracting the data, we have to create the data bunch. So, let us establish that." }, { "code": null, "e": 5513, "s": 5320, "text": "The first thing you say is what kind of item list do you have. So, in this case, it’s the list of images. Then where are you getting the list of file names from? In this case, we have folders." }, { "code": null, "e": 5564, "s": 5513, "text": "imagelist = ImageList.from_folder(path); imagelist" }, { "code": null, "e": 5832, "s": 5564, "text": "So inside an item list is an items attribute and the items attribute is the kind of thing that you gave it. It's the thing that it's going to use to create your items. So in this case, the thing you gave it is a list of file names. That's what it got from the folder." }, { "code": null, "e": 5848, "s": 5832, "text": "imagelist.items" }, { "code": null, "e": 5949, "s": 5848, "text": "When you show images, it usually shows them in RGB. In this case, we want to use a binary color map." }, { "code": null, "e": 5992, "s": 5949, "text": "defaults.cmap='binary'imagelist[22].show()" }, { "code": null, "e": 6270, "s": 5992, "text": "Once you’ve got an image item list, you then split it into training versus validation. You nearly always want validation. If you don’t, you can use the .no_split method to create an empty validation set. You can't skip it entirely. All this is defined in fastai data block API." }, { "code": null, "e": 6354, "s": 6270, "text": "splitData = imagelist.split_by_folder(train='training', valid='testing'); splitData" }, { "code": null, "e": 6594, "s": 6354, "text": "So that is always the order. First, create your item list, then decide how to split. In this case, we’re going to do it based on folders. The validation folder for MNIST is called testing , and therefore we mention that in the method also." }, { "code": null, "e": 6703, "s": 6594, "text": "Now, we want to label our data, and we want to label the data using the folder in which our data is present." }, { "code": null, "e": 6744, "s": 6703, "text": "labelist = splitData.label_from_folder()" }, { "code": null, "e": 6817, "s": 6744, "text": "So first you create the item list, then you split it, then you label it." }, { "code": null, "e": 6887, "s": 6817, "text": "x,y = labelist.train[0] or labelist.valid[0]x.show()print(x.shape, y)" }, { "code": null, "e": 7097, "s": 6887, "text": "Now, comes adding transforms. Transformation is the part of data augmentation. There is a very considerable difference between processes that we add for tabular data and transformations that we add for images." }, { "code": null, "e": 7219, "s": 7097, "text": "Processes are added once on the training data, and the same validations are carried to the validation and testing data.s." }, { "code": null, "e": 7290, "s": 7219, "text": "Transformations are applied every time we ask for the bunch of images." }, { "code": null, "e": 7725, "s": 7290, "text": "Since we are doing digit recognition, therefore we do not want to apply a default to the data because it consists of some transformations that we really do not want like flipping the number vertically/horizontally will change the number, zooming the text will change the pixels of image and image will be blurred. Therefore, we will add our transformations, and they are effortless, add random padding and a little amount of cropping." }, { "code": null, "e": 7878, "s": 7725, "text": "tfms = ([*rand_pad(padding=3, size=28, mode='zeros')], [])(empty array refers to the validaion set transforms)transformedlist = labelist.transform(tfms)" }, { "code": null, "e": 8107, "s": 7878, "text": "Now is the time for the last step, and it is to create the data bunch. Here I am not using image stats for normalization as I am not using a pre-trained model like ResNet34, ResNet56, etc. Also, I will use the batch size of 128." }, { "code": null, "e": 8205, "s": 8107, "text": "bs = 128data = transformedlist.databunch(bs=bs).normalize()x,y = data.train_ds[0]x.show()print(y)" }, { "code": null, "e": 8426, "s": 8205, "text": "What is most interesting is that the training data set now has data augmentation because we have added transforms. plot_multi is a fast.ai function that will plot the result of calling some function on each of the items." }, { "code": null, "e": 8526, "s": 8426, "text": "def _plot(i,j,ax): data.train_ds[0][0].show(ax, cmap='gray')plot_multi(_plot, 3, 3, figsize=(7, 7))" }, { "code": null, "e": 8568, "s": 8526, "text": "xb,yb = data.one_batch()xb.shape,yb.shape" }, { "code": null, "e": 8607, "s": 8568, "text": "data.show_batch(rows=3, figsize=(5,5))" }, { "code": null, "e": 8716, "s": 8607, "text": "Now, we are done with the data bunch. Now, we will create the learner and will train it through our own CNN." }, { "code": null, "e": 9111, "s": 8716, "text": "def conv(ni,nf): return nn.Conv2d(ni, nf, kernel_size=3, stride=2, padding=1)model = nn.Sequential( conv(3, 8), # 14 nn.BatchNorm2d(8), nn.ReLU(),conv(8, 16), # 7 nn.BatchNorm2d(16), nn.ReLU(),conv(16, 32), # 4 nn.BatchNorm2d(32), nn.ReLU(),conv(32, 16), # 2 nn.BatchNorm2d(16), nn.ReLU(),conv(16, 10), # 1 nn.BatchNorm2d(10), Flatten() # remove (1,1) grid)" }, { "code": null, "e": 9149, "s": 9111, "text": "Let us understand the above function." }, { "code": null, "e": 9195, "s": 9149, "text": "We are declaring the kernel size to be 3 * 3." }, { "code": null, "e": 9240, "s": 9195, "text": "We want to perform the stride-2 convolution." }, { "code": null, "e": 9332, "s": 9240, "text": "Now, We want to perform the sequential operation, that’s why we have written nn.Sequential." }, { "code": null, "e": 9522, "s": 9332, "text": "The first layer of the model is conv(3, 8). 3 implies to the number of input channels. Since our image has three input channels, therefore we have declared that number. See the image below." }, { "code": null, "e": 9655, "s": 9522, "text": "8 is the total number of channels in the output. This number implies the total number of filters, as discussed in the above section." }, { "code": null, "e": 9969, "s": 9655, "text": "The number of channels in the output of one layer is input to the next layer. Now, we have mentioned using stride-2 convolution. Therefore, we started with an image size of 28 * 28. In the second layer, it will turn down to 14 * 14, in the next layer to 7 * 7 and then to 4 * 4, then to 2 * 2 and lastly to 1 * 1." }, { "code": null, "e": 10148, "s": 9969, "text": "The output will be in the form of [128, 10, 1, 1] — each image in the batch of 128 has ten channels of 1 * 1in the output as rank three tensors. We flatten it to rank one tensor." }, { "code": null, "e": 10249, "s": 10148, "text": "In between the convolution layers, we have added batch normalization and ReLu as a non-linear layer." }, { "code": null, "e": 10323, "s": 10249, "text": "That’s all ( ͡ᴖ ͜ʖ ͡ᴖ), we have created our convolutional neural network." }, { "code": null, "e": 10387, "s": 10323, "text": "Now is the time to create the learner as defined in the fastai." }, { "code": null, "e": 10484, "s": 10387, "text": "learn = Learner(data, model, loss_func = nn.CrossEntropyLoss(), metrics=accuracy)learn.summary()" }, { "code": null, "e": 10531, "s": 10484, "text": "learn.lr_find(end_lr=100)learn.recorder.plot()" }, { "code": null, "e": 10567, "s": 10531, "text": "learn.fit_one_cycle(10, max_lr=0.1)" }, { "code": null, "e": 10688, "s": 10567, "text": "Now, let us understand the ResNet and then I will include that in our model and will see how much the accuracy improves." }, { "code": null, "e": 10749, "s": 10688, "text": "Let X be out input. As per the ResNet, instead of doing like" }, { "code": null, "e": 10770, "s": 10749, "text": "Y = conv2(conv1(X))," }, { "code": null, "e": 10787, "s": 10770, "text": "It does like so," }, { "code": null, "e": 10877, "s": 10787, "text": "Y = X + conv2(conv1(X)) — This thing is called an identity connection or skip connection." }, { "code": null, "e": 11029, "s": 10877, "text": "ResNet drastically improves the loss function surface. Without ResNets, the loss function has lots of bumps, and with ResNet, it turned down to smooth." }, { "code": null, "e": 11063, "s": 11029, "text": "We can create ResBock like below:" }, { "code": null, "e": 11289, "s": 11063, "text": "class ResBlock(nn.Module): def __init__(self, nf): super().__init__() self.conv1 = conv_layer(nf,nf) self.conv2 = conv_layer(nf,nf) def forward(self, x): return x + self.conv2(self.conv1(x))" }, { "code": null, "e": 11536, "s": 11289, "text": "Let us change our model to include the ResNet blocks. Let’s refactor that a little. Rather than saying conv, batch norm, ReLU all the time, fast.ai already has something called conv_layer which lets you create conv, batch norm, ReLU combinations." }, { "code": null, "e": 11899, "s": 11536, "text": "def conv2(ni,nf): return conv_layer(ni,nf,stride=2)model = nn.Sequential( conv2(1, 8), res_block(8), conv2(8, 16), res_block(16), conv2(16, 32), res_block(32), conv2(32, 16), res_block(16), conv2(16, 10), Flatten())learn = Learner(data, model, loss_func = nn.CrossEntropyLoss(), metrics=accuracy)learn.fit_one_cycle(12, max_lr=0.05)" } ]
Solving Problems With Dynamic Programming | by John Wittenauer | Towards Data Science
This content originally appeared on Curious Insight Dynamic programming is a really useful general technique for solving problems that involves breaking down problems into smaller overlapping sub-problems, storing the results computed from the sub-problems and reusing those results on larger chunks of the problem. Dynamic programming solutions are pretty much always more efficent than naive brute-force solutions. It’s particularly effective on problems that contain optimal substructure. Dynamic programming is related to a number of other fundamental concepts in computer science in interesting ways. Recursion, for example, is similar to (but not identical to) dynamic programming. The key difference is that in a naive recursive solution, answers to sub-problems may be computed many times. A recursive solution that caches answers to sub-problems which were already computed is called memoization, which is basically the inverse of dynamic programming. Another variation is when the sub-problems don’t actually overlap at all, in which case the technique is known as divide and conquer. Finally, dynamic programming is tied to the concept of mathematical induction and can be thought of as a specific application of inductive reasoning in practice. While the core ideas behind dynamic programming are actually pretty simple, it turns out that it’s fairly challenging to use on non-trivial problems because it’s often not obvious how to frame a difficult problem in terms of overlapping sub-problems. This is where experience and practice come in handy, which is the idea for this blog post. We’ll build both naive and “intelligent” solutions to several well-known problems and see how the problems are decomposed to use dynamic programming solutions. The code is written in basic python with no special dependencies. First we’ll look at the problem of computing numbers in the Fibonacci sequence. The problem definition is very simple — each number in the sequence is the sum of the two previous numbers in the sequence. Or, more formally: F_n=F_n−1+F_n−2, with F_0=0 and F_1=1 as the seed values. (note: Medium does not have the ability to render equations properly so I’m using the fairly hack-ish solution of displaying mathematical notation in italics...apologies if the true meaning doesn’t come through very well.) Our solution will be responsible for calculating each of Fibonacci numbers up to some defined limit. We’ll first implement a naive solution that re-calculates each number in the sequence from scratch. def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2)def all_fib(n): fibs = [] for i in range(n): fibs.append(fib(i)) return fibs Let’s try it out on a pretty small number first. %time print(all_fib(10))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Wall time: 0 ns Okay, probably too trivial. Let’s try a bit bigger... %time print(all_fib(20))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]Wall time: 5 ms The runtime was at least measurable now, but still pretty quick. Let’s try one more time... %time print(all_fib(40))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986]Wall time: 1min 9s That escalated quickly! Clearly this is a pretty bad solution. Let’s see what it looks like when applying dynamic programming. def all_fib_dp(n): fibs = [] for i in range(n): if i < 2: fibs.append(i) else: fibs.append(fibs[i - 2] + fibs[i - 1]) return fibs This time we’re saving the result at each iteration and computing new numbers as a sum of the previously saved results. Let’s see what this does to the performance of the function. %time print(all_fib_dp(40))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986]Wall time: 0 ns By not computing the full recusrive tree on each iteration, we’ve essentially reduced the running time for the first 40 numbers from ~75 seconds to virtually instant. This also happens to be a good example of the danger of naive recursive functions. Our new Fibonaci number function can compute additional values in linear time vs. exponential time for the first version. %time print(all_fib_dp(100))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073L, 4807526976L, 7778742049L, 12586269025L, 20365011074L, 32951280099L, 53316291173L, 86267571272L, 139583862445L, 225851433717L, 365435296162L, 591286729879L, 956722026041L, 1548008755920L, 2504730781961L, 4052739537881L, 6557470319842L, 10610209857723L, 17167680177565L, 27777890035288L, 44945570212853L, 72723460248141L, 117669030460994L, 190392490709135L, 308061521170129L, 498454011879264L, 806515533049393L, 1304969544928657L, 2111485077978050L, 3416454622906707L, 5527939700884757L, 8944394323791464L, 14472334024676221L, 23416728348467685L, 37889062373143906L, 61305790721611591L, 99194853094755497L, 160500643816367088L, 259695496911122585L, 420196140727489673L, 679891637638612258L, 1100087778366101931L, 1779979416004714189L, 2880067194370816120L, 4660046610375530309L, 7540113804746346429L, 12200160415121876738L, 19740274219868223167L, 31940434634990099905L, 51680708854858323072L, 83621143489848422977L, 135301852344706746049L, 218922995834555169026L]Wall time: 0 ns The Fibonacci problem is a good starter example but doesn’t really capture the challenge of representing problems in terms of optimal sub-problems because for Fibonacci numbers the answer is pretty obvious. Let’s move up one step in difficulty to a problem known as the longest increasing subsequence problem. The objective is to find the longest subsequence of a given sequence such that all elements in the subsequence are sorted in increasing order. Note that the elements do not need to be contiguous; that is, they are not required to appear next to each other. For example, in the sequence [10, 22, 9, 33, 21, 50, 41, 60, 80] the longest increasing subsequence (LIS) is [10, 22, 33, 50, 60, 80]. It turns out that it’s fairly difficult to do a “brute-force” solution to this problem. The dynamic programming solution is much more concise and a natural fit for the problem definition, so we’ll skip creating an unnecessarily complicated naive solution and jump straight to the DP solution. def find_lis(seq): n = len(seq) max_length = 1 best_seq_end = -1 # keep a chain of the values of the lis prev = [0 for i in range(n)] prev[0] = -1 # the length of the lis at each position length = [0 for i in range(n)] length[0] = 1 for i in range(1, n): length[i] = 0 prev[i] = -1 # start from index i-1 and work back to 0 for j in range(i - 1, -1, -1): if (length[j] + 1) > length[i] and seq[j] < seq[i]: # there's a number before position i that increases the lis at i length[i] = length[j] + 1 prev[i] = j if length[i] > max_length: max_length = length[i] best_seq_end = i # recover the subsequence lis = [] element = best_seq_end while element != -1: lis.append(seq[element]) element = prev[element] return lis[::-1] The intuition here is that for a given index i, we can compute the length of the longest increasing subsequence length(i) by looking at all indices j<i and if length(j)+1>i and seq[j]<seq[i] (meaning there’s a number at position jj that increases the longest subsequence at that index such that it is now longer than the longest recorded subsequence at i) then we increase length(i) by 1. It’s a bit confusing at first glance but step through it carefully and convince yourself that this solution finds the optimal subsequence. The “prev” list holds the indices of the elements that form the actual values in the subsequence. Let’s generate some test data and try it out. import numpy as np seq_small = list(np.random.randint(0, 20, 20)) seq_small[16, 10, 17, 18, 9, 0, 2, 19, 4, 3, 1, 14, 12, 6, 2, 4, 11, 5, 19, 4] Now we can run a quick test to see if it works on a small sequence. %time print(find_lis(seq_small))[0, 1, 2, 4, 5, 19]Wall time: 0 ns Just based on the eye test the output looks correct. Let’s see how well it performs on much larger sequences. seq = list(np.random.randint(0, 10000, 10000)) %time print(find_lis(seq))[29, 94, 125, 159, 262, 271, 274, 345, 375, 421, 524, 536, 668, 689, 694, 755, 763, 774, 788, 854, 916, 1018, 1022, 1098, 1136, 1154, 1172, 1237, 1325, 1361, 1400, 1401, 1406, 1450, 1498, 1633, 1693, 1745, 1765, 1793, 1835, 1949, 1997, 2069, 2072, 2096, 2157, 2336, 2345, 2468, 2519, 2529, 2624, 2630, 2924, 3103, 3291, 3321, 3380, 3546, 3635, 3657, 3668, 3703, 3775, 3836, 3850, 3961, 4002, 4004, 4039, 4060, 4128, 4361, 4377, 4424, 4432, 4460, 4465, 4493, 4540, 4595, 4693, 4732, 4735, 4766, 4831, 4850, 4873, 4908, 4940, 4969, 5013, 5073, 5087, 5139, 5144, 5271, 5280, 5299, 5300, 5355, 5393, 5430, 5536, 5538, 5559, 5565, 5822, 5891, 5895, 5906, 6157, 6199, 6286, 6369, 6431, 6450, 6510, 6533, 6577, 6585, 6683, 6701, 6740, 6745, 6829, 6853, 6863, 6872, 6884, 6923, 6925, 7009, 7019, 7028, 7040, 7170, 7235, 7304, 7356, 7377, 7416, 7490, 7495, 7662, 7676, 7703, 7808, 7925, 7971, 8036, 8073, 8282, 8295, 8332, 8342, 8360, 8429, 8454, 8499, 8557, 8585, 8639, 8649, 8725, 8759, 8831, 8860, 8899, 8969, 9046, 9146, 9161, 9245, 9270, 9374, 9451, 9465, 9515, 9522, 9525, 9527, 9664, 9770, 9781, 9787, 9914, 9993]Wall time: 4.94 s So it’s still pretty fast, but the difference is definitely noticable. At 10,000 integers in the sequence our algorithm already takes several seconds to complete. In fact, even though this solution uses dynamic programming its runtime is still O(n2). The lesson here is that dynamic programming doesn’t always result in lightning-fast solutions. There are also different ways to apply DP to the same problem. In fact there’s a solution to this problem that uses binary search trees and runs in O(nlogn) time, significantly better than the solution we just came up with. The knapsack problem is another classic dynamic programming exercise. The generalization of this problem is very old and comes in many variations, and there are actually multiple ways to tackle this problem aside from dynamic programming. Still, it’s a common example for DP exercises. The problem at its core is one of combinatorial optimization. Given a set of items, each with a mass and a value, determine the collection of items that results in the highest possible value while not exceeding some limit on the total weight. The variation we’ll look at is commonly referred to as the 0–1 knapsack problem, which restricts the number of copies of each kind of item to 0 or 1. More formally, given a set of n items each with weight w_i and value v_i along with a maximum total weight W, our objective is: maxΣv_ix_i, where Σw_ix_i≤W Let’s see what the implementation looks like then discuss why it works. def knapsack(W, w, v): # create a W x n solution matrix to store the sub-problem results n = len(v) S = [[0 for x in range(W)] for k in range(n)] for x in range(1, W): for k in range(1, n): # using this notation k is the number of items in the solution and x is the max weight of the solution, # so the initial assumption is that the optimal solution with k items at weight x is at least as good # as the optimal solution with k-1 items for the same max weight S[k][x] = S[k-1][x] # if the current item weighs less than the max weight and the optimal solution including this item is # better than the current optimum, the new optimum is the one resulting from including the current item if w[k] < x and S[k-1][x-w[k]] + v[k] > S[k][x]: S[k][x] = S[k-1][x-w[k]] + v[k] return S The intuition behind this algorithm is that once you’ve solved for the optimal combination of items at some weight x<W and with some number of items k<n, then it’s easy to solve the problem with one more item or one higher max weight because you can just check to see if the solution obtained by incorporating that item is better than the best solution you’ve already found. So how do you get the initial solution? Keep going down the rabbit hole until to reach 0 (in which case the answer is 0). At first glance it’s very hard to grasp, but that’s part of the magic of dynamic programming. Let’s run an example to see what it looks like. We’ll start with some randomly-generated weights and values. w = list(np.random.randint(0, 10, 5)) v = list(np.random.randint(0, 100, 5)) w, v([3, 9, 3, 6, 5], [40, 45, 72, 77, 16]) Now we can run the algorithm with a constraint that the weights of the items can’t add up to more than 15. knapsack(15, w, v)[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 45, 45, 45, 45], [0, 0, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 117, 117], [0, 0, 0, 0, 72, 72, 72, 77, 77, 77, 149, 149, 149, 149, 149], [0, 0, 0, 0, 72, 72, 72, 77, 77, 88, 149, 149, 149, 149, 149]] The output here is the array of optimal values for a given max weight (think of it as the column index) and max number of items (the row index). Notice how the output follows what looks sort of like a wavefront pattern. This seems to be a recurring phenomenon with dynamic programming solutions. The value in the lower right corner is the max value that we were looking for under the given constraints and is the answer to the problem. That concludes our introduction to dynamic programming! Using this technique in the real world definitely requires a lot of practice; most applications of dynamic programming are not very obvious and take some skill to discover. Personally it doesn’t come naturally to me at all and even learning these relatively simple examples took quite a bit of thought. It might seem like these sorts of problems don’t come up all that often in practice, and there’s probably some truth to that. However I’ve found that simply knowing about dynamic programming and how it fits into a more general problem-solving framework has made me a better engineer, and that in of itself makes it worth the time investment to understand. To comment on this article, check out the original post at Curious Insight Follow me on twitter to get new post updates
[ { "code": null, "e": 223, "s": 171, "text": "This content originally appeared on Curious Insight" }, { "code": null, "e": 663, "s": 223, "text": "Dynamic programming is a really useful general technique for solving problems that involves breaking down problems into smaller overlapping sub-problems, storing the results computed from the sub-problems and reusing those results on larger chunks of the problem. Dynamic programming solutions are pretty much always more efficent than naive brute-force solutions. It’s particularly effective on problems that contain optimal substructure." }, { "code": null, "e": 1428, "s": 663, "text": "Dynamic programming is related to a number of other fundamental concepts in computer science in interesting ways. Recursion, for example, is similar to (but not identical to) dynamic programming. The key difference is that in a naive recursive solution, answers to sub-problems may be computed many times. A recursive solution that caches answers to sub-problems which were already computed is called memoization, which is basically the inverse of dynamic programming. Another variation is when the sub-problems don’t actually overlap at all, in which case the technique is known as divide and conquer. Finally, dynamic programming is tied to the concept of mathematical induction and can be thought of as a specific application of inductive reasoning in practice." }, { "code": null, "e": 1996, "s": 1428, "text": "While the core ideas behind dynamic programming are actually pretty simple, it turns out that it’s fairly challenging to use on non-trivial problems because it’s often not obvious how to frame a difficult problem in terms of overlapping sub-problems. This is where experience and practice come in handy, which is the idea for this blog post. We’ll build both naive and “intelligent” solutions to several well-known problems and see how the problems are decomposed to use dynamic programming solutions. The code is written in basic python with no special dependencies." }, { "code": null, "e": 2219, "s": 1996, "text": "First we’ll look at the problem of computing numbers in the Fibonacci sequence. The problem definition is very simple — each number in the sequence is the sum of the two previous numbers in the sequence. Or, more formally:" }, { "code": null, "e": 2277, "s": 2219, "text": "F_n=F_n−1+F_n−2, with F_0=0 and F_1=1 as the seed values." }, { "code": null, "e": 2500, "s": 2277, "text": "(note: Medium does not have the ability to render equations properly so I’m using the fairly hack-ish solution of displaying mathematical notation in italics...apologies if the true meaning doesn’t come through very well.)" }, { "code": null, "e": 2701, "s": 2500, "text": "Our solution will be responsible for calculating each of Fibonacci numbers up to some defined limit. We’ll first implement a naive solution that re-calculates each number in the sequence from scratch." }, { "code": null, "e": 2903, "s": 2701, "text": "def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2)def all_fib(n): fibs = [] for i in range(n): fibs.append(fib(i)) return fibs" }, { "code": null, "e": 2952, "s": 2903, "text": "Let’s try it out on a pretty small number first." }, { "code": null, "e": 3025, "s": 2952, "text": "%time print(all_fib(10))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Wall time: 0 ns" }, { "code": null, "e": 3079, "s": 3025, "text": "Okay, probably too trivial. Let’s try a bit bigger..." }, { "code": null, "e": 3203, "s": 3079, "text": "%time print(all_fib(20))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]Wall time: 5 ms" }, { "code": null, "e": 3295, "s": 3203, "text": "The runtime was at least measurable now, but still pretty quick. Let’s try one more time..." }, { "code": null, "e": 3588, "s": 3295, "text": "%time print(all_fib(40))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986]Wall time: 1min 9s" }, { "code": null, "e": 3715, "s": 3588, "text": "That escalated quickly! Clearly this is a pretty bad solution. Let’s see what it looks like when applying dynamic programming." }, { "code": null, "e": 3892, "s": 3715, "text": "def all_fib_dp(n): fibs = [] for i in range(n): if i < 2: fibs.append(i) else: fibs.append(fibs[i - 2] + fibs[i - 1]) return fibs" }, { "code": null, "e": 4073, "s": 3892, "text": "This time we’re saving the result at each iteration and computing new numbers as a sum of the previously saved results. Let’s see what this does to the performance of the function." }, { "code": null, "e": 4366, "s": 4073, "text": "%time print(all_fib_dp(40))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986]Wall time: 0 ns" }, { "code": null, "e": 4738, "s": 4366, "text": "By not computing the full recusrive tree on each iteration, we’ve essentially reduced the running time for the first 40 numbers from ~75 seconds to virtually instant. This also happens to be a good example of the danger of naive recursive functions. Our new Fibonaci number function can compute additional values in linear time vs. exponential time for the first version." }, { "code": null, "e": 6086, "s": 4738, "text": "%time print(all_fib_dp(100))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073L, 4807526976L, 7778742049L, 12586269025L, 20365011074L, 32951280099L, 53316291173L, 86267571272L, 139583862445L, 225851433717L, 365435296162L, 591286729879L, 956722026041L, 1548008755920L, 2504730781961L, 4052739537881L, 6557470319842L, 10610209857723L, 17167680177565L, 27777890035288L, 44945570212853L, 72723460248141L, 117669030460994L, 190392490709135L, 308061521170129L, 498454011879264L, 806515533049393L, 1304969544928657L, 2111485077978050L, 3416454622906707L, 5527939700884757L, 8944394323791464L, 14472334024676221L, 23416728348467685L, 37889062373143906L, 61305790721611591L, 99194853094755497L, 160500643816367088L, 259695496911122585L, 420196140727489673L, 679891637638612258L, 1100087778366101931L, 1779979416004714189L, 2880067194370816120L, 4660046610375530309L, 7540113804746346429L, 12200160415121876738L, 19740274219868223167L, 31940434634990099905L, 51680708854858323072L, 83621143489848422977L, 135301852344706746049L, 218922995834555169026L]Wall time: 0 ns" }, { "code": null, "e": 6788, "s": 6086, "text": "The Fibonacci problem is a good starter example but doesn’t really capture the challenge of representing problems in terms of optimal sub-problems because for Fibonacci numbers the answer is pretty obvious. Let’s move up one step in difficulty to a problem known as the longest increasing subsequence problem. The objective is to find the longest subsequence of a given sequence such that all elements in the subsequence are sorted in increasing order. Note that the elements do not need to be contiguous; that is, they are not required to appear next to each other. For example, in the sequence [10, 22, 9, 33, 21, 50, 41, 60, 80] the longest increasing subsequence (LIS) is [10, 22, 33, 50, 60, 80]." }, { "code": null, "e": 7081, "s": 6788, "text": "It turns out that it’s fairly difficult to do a “brute-force” solution to this problem. The dynamic programming solution is much more concise and a natural fit for the problem definition, so we’ll skip creating an unnecessarily complicated naive solution and jump straight to the DP solution." }, { "code": null, "e": 7977, "s": 7081, "text": "def find_lis(seq): n = len(seq) max_length = 1 best_seq_end = -1 # keep a chain of the values of the lis prev = [0 for i in range(n)] prev[0] = -1 # the length of the lis at each position length = [0 for i in range(n)] length[0] = 1 for i in range(1, n): length[i] = 0 prev[i] = -1 # start from index i-1 and work back to 0 for j in range(i - 1, -1, -1): if (length[j] + 1) > length[i] and seq[j] < seq[i]: # there's a number before position i that increases the lis at i length[i] = length[j] + 1 prev[i] = j if length[i] > max_length: max_length = length[i] best_seq_end = i # recover the subsequence lis = [] element = best_seq_end while element != -1: lis.append(seq[element]) element = prev[element] return lis[::-1]" }, { "code": null, "e": 8603, "s": 7977, "text": "The intuition here is that for a given index i, we can compute the length of the longest increasing subsequence length(i) by looking at all indices j<i and if length(j)+1>i and seq[j]<seq[i] (meaning there’s a number at position jj that increases the longest subsequence at that index such that it is now longer than the longest recorded subsequence at i) then we increase length(i) by 1. It’s a bit confusing at first glance but step through it carefully and convince yourself that this solution finds the optimal subsequence. The “prev” list holds the indices of the elements that form the actual values in the subsequence." }, { "code": null, "e": 8649, "s": 8603, "text": "Let’s generate some test data and try it out." }, { "code": null, "e": 8796, "s": 8649, "text": "import numpy as np seq_small = list(np.random.randint(0, 20, 20)) seq_small[16, 10, 17, 18, 9, 0, 2, 19, 4, 3, 1, 14, 12, 6, 2, 4, 11, 5, 19, 4]" }, { "code": null, "e": 8864, "s": 8796, "text": "Now we can run a quick test to see if it works on a small sequence." }, { "code": null, "e": 8931, "s": 8864, "text": "%time print(find_lis(seq_small))[0, 1, 2, 4, 5, 19]Wall time: 0 ns" }, { "code": null, "e": 9041, "s": 8931, "text": "Just based on the eye test the output looks correct. Let’s see how well it performs on much larger sequences." }, { "code": null, "e": 10244, "s": 9041, "text": "seq = list(np.random.randint(0, 10000, 10000)) %time print(find_lis(seq))[29, 94, 125, 159, 262, 271, 274, 345, 375, 421, 524, 536, 668, 689, 694, 755, 763, 774, 788, 854, 916, 1018, 1022, 1098, 1136, 1154, 1172, 1237, 1325, 1361, 1400, 1401, 1406, 1450, 1498, 1633, 1693, 1745, 1765, 1793, 1835, 1949, 1997, 2069, 2072, 2096, 2157, 2336, 2345, 2468, 2519, 2529, 2624, 2630, 2924, 3103, 3291, 3321, 3380, 3546, 3635, 3657, 3668, 3703, 3775, 3836, 3850, 3961, 4002, 4004, 4039, 4060, 4128, 4361, 4377, 4424, 4432, 4460, 4465, 4493, 4540, 4595, 4693, 4732, 4735, 4766, 4831, 4850, 4873, 4908, 4940, 4969, 5013, 5073, 5087, 5139, 5144, 5271, 5280, 5299, 5300, 5355, 5393, 5430, 5536, 5538, 5559, 5565, 5822, 5891, 5895, 5906, 6157, 6199, 6286, 6369, 6431, 6450, 6510, 6533, 6577, 6585, 6683, 6701, 6740, 6745, 6829, 6853, 6863, 6872, 6884, 6923, 6925, 7009, 7019, 7028, 7040, 7170, 7235, 7304, 7356, 7377, 7416, 7490, 7495, 7662, 7676, 7703, 7808, 7925, 7971, 8036, 8073, 8282, 8295, 8332, 8342, 8360, 8429, 8454, 8499, 8557, 8585, 8639, 8649, 8725, 8759, 8831, 8860, 8899, 8969, 9046, 9146, 9161, 9245, 9270, 9374, 9451, 9465, 9515, 9522, 9525, 9527, 9664, 9770, 9781, 9787, 9914, 9993]Wall time: 4.94 s" }, { "code": null, "e": 10814, "s": 10244, "text": "So it’s still pretty fast, but the difference is definitely noticable. At 10,000 integers in the sequence our algorithm already takes several seconds to complete. In fact, even though this solution uses dynamic programming its runtime is still O(n2). The lesson here is that dynamic programming doesn’t always result in lightning-fast solutions. There are also different ways to apply DP to the same problem. In fact there’s a solution to this problem that uses binary search trees and runs in O(nlogn) time, significantly better than the solution we just came up with." }, { "code": null, "e": 11100, "s": 10814, "text": "The knapsack problem is another classic dynamic programming exercise. The generalization of this problem is very old and comes in many variations, and there are actually multiple ways to tackle this problem aside from dynamic programming. Still, it’s a common example for DP exercises." }, { "code": null, "e": 11621, "s": 11100, "text": "The problem at its core is one of combinatorial optimization. Given a set of items, each with a mass and a value, determine the collection of items that results in the highest possible value while not exceeding some limit on the total weight. The variation we’ll look at is commonly referred to as the 0–1 knapsack problem, which restricts the number of copies of each kind of item to 0 or 1. More formally, given a set of n items each with weight w_i and value v_i along with a maximum total weight W, our objective is:" }, { "code": null, "e": 11649, "s": 11621, "text": "maxΣv_ix_i, where Σw_ix_i≤W" }, { "code": null, "e": 11721, "s": 11649, "text": "Let’s see what the implementation looks like then discuss why it works." }, { "code": null, "e": 12615, "s": 11721, "text": "def knapsack(W, w, v): # create a W x n solution matrix to store the sub-problem results n = len(v) S = [[0 for x in range(W)] for k in range(n)] for x in range(1, W): for k in range(1, n): # using this notation k is the number of items in the solution and x is the max weight of the solution, # so the initial assumption is that the optimal solution with k items at weight x is at least as good # as the optimal solution with k-1 items for the same max weight S[k][x] = S[k-1][x] # if the current item weighs less than the max weight and the optimal solution including this item is # better than the current optimum, the new optimum is the one resulting from including the current item if w[k] < x and S[k-1][x-w[k]] + v[k] > S[k][x]: S[k][x] = S[k-1][x-w[k]] + v[k] return S" }, { "code": null, "e": 13315, "s": 12615, "text": "The intuition behind this algorithm is that once you’ve solved for the optimal combination of items at some weight x<W and with some number of items k<n, then it’s easy to solve the problem with one more item or one higher max weight because you can just check to see if the solution obtained by incorporating that item is better than the best solution you’ve already found. So how do you get the initial solution? Keep going down the rabbit hole until to reach 0 (in which case the answer is 0). At first glance it’s very hard to grasp, but that’s part of the magic of dynamic programming. Let’s run an example to see what it looks like. We’ll start with some randomly-generated weights and values." }, { "code": null, "e": 13438, "s": 13315, "text": "w = list(np.random.randint(0, 10, 5)) v = list(np.random.randint(0, 100, 5)) w, v([3, 9, 3, 6, 5], [40, 45, 72, 77, 16])" }, { "code": null, "e": 13545, "s": 13438, "text": "Now we can run the algorithm with a constraint that the weights of the items can’t add up to more than 15." }, { "code": null, "e": 13849, "s": 13545, "text": "knapsack(15, w, v)[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 45, 45, 45, 45], [0, 0, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 117, 117], [0, 0, 0, 0, 72, 72, 72, 77, 77, 77, 149, 149, 149, 149, 149], [0, 0, 0, 0, 72, 72, 72, 77, 77, 88, 149, 149, 149, 149, 149]]" }, { "code": null, "e": 14285, "s": 13849, "text": "The output here is the array of optimal values for a given max weight (think of it as the column index) and max number of items (the row index). Notice how the output follows what looks sort of like a wavefront pattern. This seems to be a recurring phenomenon with dynamic programming solutions. The value in the lower right corner is the max value that we were looking for under the given constraints and is the answer to the problem." }, { "code": null, "e": 15000, "s": 14285, "text": "That concludes our introduction to dynamic programming! Using this technique in the real world definitely requires a lot of practice; most applications of dynamic programming are not very obvious and take some skill to discover. Personally it doesn’t come naturally to me at all and even learning these relatively simple examples took quite a bit of thought. It might seem like these sorts of problems don’t come up all that often in practice, and there’s probably some truth to that. However I’ve found that simply knowing about dynamic programming and how it fits into a more general problem-solving framework has made me a better engineer, and that in of itself makes it worth the time investment to understand." }, { "code": null, "e": 15075, "s": 15000, "text": "To comment on this article, check out the original post at Curious Insight" } ]
Python - math.comb() method - GeeksforGeeks
23 Jan, 2020 Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.comb() method in Python is used to get the number of ways to choose k items from n items without repetition and without order. It basically evaluates to n! / (k! * (n – k)!) when k n. It is also known as binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)n.This method is new in Python version 3.8. Syntax: math.comb(n, k) Parameters:n: A non-negative integerk: A non-negative integer Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order. Code #1: Use of math.comb() method # Python Program to explain math.comb() method # Importing math moduleimport math n = 10k = 2 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk) n = 5k = 3 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk) 45 10 Code #2: When k > n # Python Program to explain math.comb() method # Importing math moduleimport math # When k > n # math.comb(n, k) returns 0.n = 3k = 5 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk) 0 Code #3: Use of math.comb() method to find coefficient of k-th term in binomial expansion of expression (1 + x)n # Python Program to explain math.comb() method # Importing math moduleimport math n = 5k = 2 # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk) n = 8k = 3 # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk) 10 56 Reference: Python math library Python math-library Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24738, "s": 24710, "text": "\n23 Jan, 2020" }, { "code": null, "e": 25237, "s": 24738, "text": "Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.comb() method in Python is used to get the number of ways to choose k items from n items without repetition and without order. It basically evaluates to n! / (k! * (n – k)!) when k n. It is also known as binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)n.This method is new in Python version 3.8." }, { "code": null, "e": 25261, "s": 25237, "text": "Syntax: math.comb(n, k)" }, { "code": null, "e": 25323, "s": 25261, "text": "Parameters:n: A non-negative integerk: A non-negative integer" }, { "code": null, "e": 25454, "s": 25323, "text": "Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order." }, { "code": null, "e": 25489, "s": 25454, "text": "Code #1: Use of math.comb() method" }, { "code": "# Python Program to explain math.comb() method # Importing math moduleimport math n = 10k = 2 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk) n = 5k = 3 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk)", "e": 25851, "s": 25489, "text": null }, { "code": null, "e": 25858, "s": 25851, "text": "45\n10\n" }, { "code": null, "e": 25878, "s": 25858, "text": "Code #2: When k > n" }, { "code": "# Python Program to explain math.comb() method # Importing math moduleimport math # When k > n # math.comb(n, k) returns 0.n = 3k = 5 # Get the number of ways to choose# k items from n items without# repetition and without ordernCk = math.comb(n, k)print(nCk)", "e": 26141, "s": 25878, "text": null }, { "code": null, "e": 26144, "s": 26141, "text": "0\n" }, { "code": null, "e": 26257, "s": 26144, "text": "Code #3: Use of math.comb() method to find coefficient of k-th term in binomial expansion of expression (1 + x)n" }, { "code": "# Python Program to explain math.comb() method # Importing math moduleimport math n = 5k = 2 # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk) n = 8k = 3 # Find the coefficient of k-th# term in the expansion of # expression (1 + x)^nnCk = math.comb(n, k)print(nCk)", "e": 26588, "s": 26257, "text": null }, { "code": null, "e": 26595, "s": 26588, "text": "10\n56\n" }, { "code": null, "e": 26626, "s": 26595, "text": "Reference: Python math library" }, { "code": null, "e": 26646, "s": 26626, "text": "Python math-library" }, { "code": null, "e": 26676, "s": 26646, "text": "Python math-library-functions" }, { "code": null, "e": 26683, "s": 26676, "text": "Python" }, { "code": null, "e": 26781, "s": 26683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26790, "s": 26781, "text": "Comments" }, { "code": null, "e": 26803, "s": 26790, "text": "Old Comments" }, { "code": null, "e": 26821, "s": 26803, "text": "Python Dictionary" }, { "code": null, "e": 26853, "s": 26821, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26875, "s": 26853, "text": "Enumerate() in Python" }, { "code": null, "e": 26910, "s": 26875, "text": "Read a file line by line in Python" }, { "code": null, "e": 26952, "s": 26910, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26996, "s": 26952, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27017, "s": 26996, "text": "Python OOPs Concepts" }, { "code": null, "e": 27054, "s": 27017, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27083, "s": 27054, "text": "*args and **kwargs in Python" } ]
Hide the cursor in a webpage using CSS and JavaScript - GeeksforGeeks
25 Jun, 2019 Given an HTML document and the task is to hide the cursor from the given element using CSS and JavaScript. Approach: First, select the element where cursor element need to hide. Add CSS style cursor:none to the a class. Add the class name (class name of CSS style cursor:none) to the particular element where cursor element to be hide. Example 1: This example hides the cursor from the <div> element. <!DOCTYPE HTML> <html> <head> <title> Hide the cursor in a element using CSS and JavaScript </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } /* CSS style to hide cursor element */ .newClass { cursor: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to hide cursor element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = "Click on button to hide the cursor from DIV."; /* Function to add class name to hide cursor element */ function GFG_Fun() { div.classList.add("newClass"); down.innerHTML = "Cursor is removed from DIV!"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example hides the cursor from the <body> of a web-page. <!DOCTYPE HTML> <html> <head> <title> Hide the cursor in a element using CSS and JavaScript </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } /* CSS style to hide cursor element */ .newClass { cursor: none; } </style> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "GFG_DIV"> This is Div box. </div> <br> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to hide cursor element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var body = document.getElementById('body'); up.innerHTML = "Click on button to hide the cursor from DIV."; /* Function to add class name to hide cursor element */ function GFG_Fun() { body.classList.add("newClass"); down.innerHTML = "Cursor is removed from body!"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: CSS-Misc JavaScript-Misc CSS JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Primer CSS Flexbox Flex Direction HTML Course | First Web Page | Printing Hello World How to position a div at the bottom of its container using CSS? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Hide or show elements in HTML using display property Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 24265, "s": 24237, "text": "\n25 Jun, 2019" }, { "code": null, "e": 24372, "s": 24265, "text": "Given an HTML document and the task is to hide the cursor from the given element using CSS and JavaScript." }, { "code": null, "e": 24382, "s": 24372, "text": "Approach:" }, { "code": null, "e": 24443, "s": 24382, "text": "First, select the element where cursor element need to hide." }, { "code": null, "e": 24485, "s": 24443, "text": "Add CSS style cursor:none to the a class." }, { "code": null, "e": 24601, "s": 24485, "text": "Add the class name (class name of CSS style cursor:none) to the particular element where cursor element to be hide." }, { "code": null, "e": 24666, "s": 24601, "text": "Example 1: This example hides the cursor from the <div> element." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Hide the cursor in a element using CSS and JavaScript </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } /* CSS style to hide cursor element */ .newClass { cursor: none; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to hide cursor element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var div = document.getElementById('GFG_DIV'); up.innerHTML = \"Click on button to hide the cursor from DIV.\"; /* Function to add class name to hide cursor element */ function GFG_Fun() { div.classList.add(\"newClass\"); down.innerHTML = \"Cursor is removed from DIV!\"; } </script> </body> </html> ", "e": 26339, "s": 24666, "text": null }, { "code": null, "e": 26347, "s": 26339, "text": "Output:" }, { "code": null, "e": 26378, "s": 26347, "text": "Before clicking on the button:" }, { "code": null, "e": 26408, "s": 26378, "text": "After clicking on the button:" }, { "code": null, "e": 26480, "s": 26408, "text": "Example 2: This example hides the cursor from the <body> of a web-page." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Hide the cursor in a element using CSS and JavaScript </title> <style> #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } /* CSS style to hide cursor element */ .newClass { cursor: none; } </style> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <div id = \"GFG_DIV\"> This is Div box. </div> <br> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to hide cursor element --> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var body = document.getElementById('body'); up.innerHTML = \"Click on button to hide the cursor from DIV.\"; /* Function to add class name to hide cursor element */ function GFG_Fun() { body.classList.add(\"newClass\"); down.innerHTML = \"Cursor is removed from body!\"; } </script> </body> </html> ", "e": 28173, "s": 26480, "text": null }, { "code": null, "e": 28181, "s": 28173, "text": "Output:" }, { "code": null, "e": 28212, "s": 28181, "text": "Before clicking on the button:" }, { "code": null, "e": 28242, "s": 28212, "text": "After clicking on the button:" }, { "code": null, "e": 28251, "s": 28242, "text": "CSS-Misc" }, { "code": null, "e": 28267, "s": 28251, "text": "JavaScript-Misc" }, { "code": null, "e": 28271, "s": 28267, "text": "CSS" }, { "code": null, "e": 28282, "s": 28271, "text": "JavaScript" }, { "code": null, "e": 28299, "s": 28282, "text": "Web Technologies" }, { "code": null, "e": 28326, "s": 28299, "text": "Web technologies Questions" }, { "code": null, "e": 28424, "s": 28326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28433, "s": 28424, "text": "Comments" }, { "code": null, "e": 28446, "s": 28433, "text": "Old Comments" }, { "code": null, "e": 28504, "s": 28446, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28541, "s": 28504, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28575, "s": 28541, "text": "Primer CSS Flexbox Flex Direction" }, { "code": null, "e": 28627, "s": 28575, "text": "HTML Course | First Web Page | Printing Hello World" }, { "code": null, "e": 28691, "s": 28627, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28736, "s": 28691, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28805, "s": 28736, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 28858, "s": 28805, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28930, "s": 28858, "text": "Differences between Functional Components and Class Components in React" } ]
C# | Type.GetInterfaces() Method - GeeksforGeeks
11 Aug, 2021 Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class. Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inherited by the current Type or an empty array of type Type if no interfaces are implemented or inherited by the current Type. Below programs illustrate the use of Type.GetInterfaces() Method: Example 1: C# // C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // Getting interface of specified name // using GetField(String) Method Type[] minterface = objType.GetInterfaces(); // Display the Result Console.WriteLine("Interface present in type {0}", objType); for (int i = 0; i < minterface.Length; i++) Console.WriteLine(" {0}", minterface[i]); }} Interface present in type System.Int32 System.IFormattable System.IComparable System.IComparable`1[System.Int32] System.IConvertible System.IEquatable`1[System.Int32] Example 2: For if no public field is defined C# // C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(string); // Getting interface of specified name // using GetField(String) Method Type[] minterface = objType.GetInterfaces(); // Display the Result Console.WriteLine("Interface present in type {0}", objType); for (int i = 0; i < minterface.Length; i++) Console.WriteLine(" {0}", minterface[i]); }} Interface present in type System.String System.ICloneable System.Collections.Generic.IEnumerable`1[System.Char] System.IComparable System.IComparable`1[System.String] System.IConvertible System.Collections.IEnumerable System.IEquatable`1[System.String] Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.getinterfaces?view=netframework-4.8 adnanirshad158 CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# | Delegates Introduction to .NET Framework C# Dictionary with examples Difference between Ref and Out keywords in C# Partial Classes in C# Extension Method in C# Top 50 C# Interview Questions & Answers Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework C# | Encapsulation
[ { "code": null, "e": 23675, "s": 23647, "text": "\n11 Aug, 2021" }, { "code": null, "e": 23818, "s": 23675, "text": "Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class." }, { "code": null, "e": 24102, "s": 23818, "text": "Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inherited by the current Type or an empty array of type Type if no interfaces are implemented or inherited by the current Type. " }, { "code": null, "e": 24168, "s": 24102, "text": "Below programs illustrate the use of Type.GetInterfaces() Method:" }, { "code": null, "e": 24180, "s": 24168, "text": "Example 1: " }, { "code": null, "e": 24183, "s": 24180, "text": "C#" }, { "code": "// C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // Getting interface of specified name // using GetField(String) Method Type[] minterface = objType.GetInterfaces(); // Display the Result Console.WriteLine(\"Interface present in type {0}\", objType); for (int i = 0; i < minterface.Length; i++) Console.WriteLine(\" {0}\", minterface[i]); }}", "e": 24809, "s": 24183, "text": null }, { "code": null, "e": 24981, "s": 24809, "text": "Interface present in type System.Int32\n System.IFormattable\n System.IComparable\n System.IComparable`1[System.Int32]\n System.IConvertible\n System.IEquatable`1[System.Int32]" }, { "code": null, "e": 25028, "s": 24983, "text": "Example 2: For if no public field is defined" }, { "code": null, "e": 25031, "s": 25028, "text": "C#" }, { "code": "// C# program to demonstrate the// Type.GetInterfaces() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(string); // Getting interface of specified name // using GetField(String) Method Type[] minterface = objType.GetInterfaces(); // Display the Result Console.WriteLine(\"Interface present in type {0}\", objType); for (int i = 0; i < minterface.Length; i++) Console.WriteLine(\" {0}\", minterface[i]); }}", "e": 25660, "s": 25031, "text": null }, { "code": null, "e": 25920, "s": 25660, "text": "Interface present in type System.String\n System.ICloneable\n System.Collections.Generic.IEnumerable`1[System.Char]\n System.IComparable\n System.IComparable`1[System.String]\n System.IConvertible\n System.Collections.IEnumerable\n System.IEquatable`1[System.String]" }, { "code": null, "e": 25933, "s": 25922, "text": "Reference:" }, { "code": null, "e": 26025, "s": 25933, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getinterfaces?view=netframework-4.8" }, { "code": null, "e": 26042, "s": 26027, "text": "adnanirshad158" }, { "code": null, "e": 26056, "s": 26042, "text": "CSharp-method" }, { "code": null, "e": 26074, "s": 26056, "text": "CSharp-Type-Class" }, { "code": null, "e": 26077, "s": 26074, "text": "C#" }, { "code": null, "e": 26175, "s": 26077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26184, "s": 26175, "text": "Comments" }, { "code": null, "e": 26197, "s": 26184, "text": "Old Comments" }, { "code": null, "e": 26220, "s": 26197, "text": "C# | Method Overriding" }, { "code": null, "e": 26235, "s": 26220, "text": "C# | Delegates" }, { "code": null, "e": 26266, "s": 26235, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26294, "s": 26266, "text": "C# Dictionary with examples" }, { "code": null, "e": 26340, "s": 26294, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26362, "s": 26340, "text": "Partial Classes in C#" }, { "code": null, "e": 26385, "s": 26362, "text": "Extension Method in C#" }, { "code": null, "e": 26425, "s": 26385, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26512, "s": 26425, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" } ]
Run More Trick Plays. An analysis of NFL trick plays... | by Blake Atkinson | Towards Data Science
Trick plays in football are one of the most fun parts of the game. Double reverses, fake field goals, and flea flickers usually make highlight reels. They are high variance in nature: either you catch the defense off guard and score an easy touchdown, or you have your running back throw a duck into double coverage and give the other team the ball on a silver platter. The high-variance nature of trick plays is intuitive to anyone who watches a lot of football. What might not be intuitive is their actual value. Until recently, the data required to objectively evaluate trick plays was not easily accessible to the public. Thanks to great work by Ron Yurko, and great tutorials by Ben Baldwin and Github user @Deryck97, any schmuck such as myself can spend a couple hours analyzing the value goofy plays over a 10 year period. How do you capture the value of a play? Obviously a 50-yard completion is worth more than a 2 yard run in almost all cases. However, is a 4 yard run on first down worth more than a 1 yard 3rd down conversion? That’s a difficult question to precisely answer. It’s clear however that not all yards are created equal. A screen pass to end the half against prevent defense might rack up 30 yards as time runs out. All that does is pad stats. Any NFL coach would rather have a 3rd down conversion in a key situation no matter how short. Ron Yurko authored a paper detailing an Expected Points Added metric. In the paper (found here), he is able to determine the amount of points a team is expected to score from any point during the game. If, after a play, that expected points metric is higher, then the play added expected points. Of course, a play such as a sack or interception will result in negative EPA. Obviously, 90+ yard offensive plays will have the highest EPA and Redzone turnovers have the worst EPA. Here are the top 5 EPA plays in the dataset: Description (3:15) (Shotgun) B.Roethlisberger pass deep middle to J.Smith-Schuster for 97 yards, TOUCHDOWN. EPA 9.5Description (10:06) (Shotgun) C.Johnson up the middle for 91 yards, TOUCHDOWN. EPA 9.3Description (7:44) (Shotgun) C.Palmer pass short middle to M.Floyd for 91 yards, TOUCHDOWN. EPA 9.2Description (8:51) (Shotgun) P.Mahomes pass deep middle to D.Robinson for 89 yards, TOUCHDOWN. PENALTY on KC-D.Robinson, Taunting, 15 yards, enforced between downs. EPA 9.1Description (11:51) (Shotgun) D.Carr pass deep middle to A.Cooper for 87 yards, TOUCHDOWN. EPA 8.9 You get the idea. Here are the bottom 5: Description (12:14) (No Huddle, Shotgun) M.Vick to WAS 10 for -6 yards (R.Kerrigan). FUMBLES (R.Kerrigan), touched at WAS 10, RECOVERED by WAS-D.Hall at WAS 25. D.Hall for 75 yards, TOUCHDOWN. Lateral batted by 91 - Kerrigan The Replay Assistant challenged the backward pass ruling, and the play was Upheld. EPA -12.8Description (11:14) (Shotgun) J.Tuel pass short right intended for T.Graham INTERCEPTED by S.Smith at KC 0. S.Smith for 100 yards, TOUCHDOWN. EPA -12.7Description (6:05) (Shotgun) M.Cassel sacked at DEN 25 for -17 yards (M.Haggan). FUMBLES (M.Haggan), RECOVERED by DEN-J.Hunter at DEN 25. J.Hunter for 75 yards, TOUCHDOWN. EPA -12.1Description (2:51) M.Vick pass short left intended for B.Celek INTERCEPTED by P.Robinson at NO 1. P.Robinson for 99 yards, TOUCHDOWN. PENALTY on PHI-M.Vick, Low Block, 15 yards, enforced between downs. The penalty for a low block during the interception return will be assessed on the ensuing kickoff. EPA -12.1Description (7:50) (Shotgun) E.Manning pass short left intended for H.Nicks INTERCEPTED by B.McCann at DAL -1. B.McCann for 101 yards, TOUCHDOWN. EPA -12.1 EPA is a funny thing, since on offense it can be greater than a touchdown. That makes sense, because if you’re backed up against your own endzone, you’re expected 1) not to score on the drive and 2) the other team is more likely to score on their next drive because of the short field. It can also be -12, because in the redzone 1) you’re expected to score around 5 points on average, and 2) the next possession for the defensive team is supposed to be post-kickoff, probably on their own half of the field. Now that we have a metric for the value of a play, we can start grouping types of plays together and comparing them. For example, taken from @Deryck97’s tutorial linked above, a comparison of rush vs. pass plays in 2018: So, using nflscrapR data, how do we know if a play is a trick play? Unfortunately there’s no easy indicator variable that says ‘trick play’. Instead, we have to come up with creative ways to identify them. The easiest plays to start with are fake kicks. Most play descriptions contain the formation of the play. If a play is labeled ‘Punt formation’ or ‘Field Goal formation’, yet the play type is a run or a pass, then it is likely to be a fake. I had to manually filter some other play types, like when the punter muffs a snap and aborts the play, but that was pretty easy. Here’s the python code: punts = df.loc[df.desc.str.contains('punt|Punt')]fake_punts = punts.loc[(punts['play_type']=='run')|(punts['play_type']=='pass')]# drop enforced penaltiesfake_punts = fake_punts.loc[fake_punts.penalty!=1]# drop non enforced penaltiesfake_punts =fake_punts.loc[~fake_punts.desc.str.contains('Penalty')]# drop punter mishandles fake_punts=fake_punts.loc[~fake_punts.desc.str.contains('Aborted|Shotgun')] # drop plays where punter intentionally runs out of end zone (not likely to fake a punt in own redzone)fake_punts = fake_punts.loc[~fake_punts.desc.str.contains('SAFETY')] # drop plays without descriptionfake_punts.dropna(subset=['desc'], inplace=True) I then apply the same filters to plays that did end in an actual punt. There ended up being 177 instances of fakes that I could pick up out of about 22,000 punt attempts (regular season and playoffs). A fake rate of less than 1%! Let’s come up with some baselines as well. I’ll show the average EPA of a punt, the average EPA of a pass play, the average EPA of a run play, and the average EPA of a pass by Tom Brady 🐐. Wow! Fake punts are worth about seven times as much as a Tom Brady pass. Of course, the standard deviation of the EPA is much higher too. The standard deviation of the EPA of non-fake punts were 1.16, while the standard deviation of fake punts was 3.17. Obviously, if you fail a fake, then you have a large negative EPA. Are fake field goals just as valuable? According to my simple analysis, no. Throwing out fumbles, bad snaps, penalties, etc — the EPA of a fake field goal is 0.06. That’s higher than your average pass, but not super exciting since I ran it after the fake punt numbers. I believe this is because what you’re giving up by forgoing a field goal. If you fail a fake field goal, you lose a few expected points you would’ve gotten from the attempt. If all you’re doing is getting a first down, you’re not even gaining that many expected points. They have a similarly large standard deviation like the fake punts. So if you’re trailing a few points, you still might be better off rolling the dice and going with a fake. Trick run plays and pass plays are not as easy to isolate unfortunately. As a disclaimer, the point this article was to start playing with the NFL play-by-play data. I’m not writing a dissertation on fake plays. So while I did go to lengths to isolate trick plays successfully, I’m not claiming 100% accuracy or the best possible process. Let’s start with passes. I began by throwing out obvious plays (penalties, two-point conversion attempts) as well as plays I’ve already analyzed (kick formations). I also threw out plays with extreme win probabilities (<5% & >95% win probability). The idea there is to avoid desperate late-game lateral plays like the hook and latter. I then searched play descriptions for flea flickers and passes by players with less than 30 attempts in the data set. Flea flickers cover laterals to the QB, and in theory, any other trick pass would involve a lateral to a running back or wide receiver that doesn’t normally pass it. Finally, I black-listed QBs that only came in for a very brief period of time and were picked up by my filters. They were easy to find because a whole series of plays sticks out in the descriptions. Almost there. For run plays, I isolated plays that had a description of lateral or reverse. Luckily, there weren’t many cases of defensive players lateraling after a fumble recovery. I ended up with a sample of 180 plays (manually removed a weird one or two). I made the choice to exclude two-point conversion attempts, so unfortunately this beauty wasn’t included: Whew. Here are the results: I was surprised to find that reverses and lateral run plays were so valuable! In theory, they’re like having a player twice as good as Tom Brady passing the ball. Since running plays aren’t usually as valuable as passing plays, I expected trick passes to have higher EPA. Trick passes are still valuable, but a lot of the EPA was driven by flea-flickers alone. In fact, only counting running back and WR passes (n=194), the EPA was 0.024 — worse than a normal pass! Flea-flickers, when only grouped by themselves (n=66), had an EPA of 0.3 — very valuable. I guess the risk of your non-QB throwing an interception is too high. Of course, if a team fakes punts all the time then defenses will adjust and the EPA will go down. The appropriate criticism here is that the novelty of the play is what makes them valuable. Still, my analysis suggests that teams should definitely run more reverses and fake punts. On a different note, I would argue that risk tolerance isn’t a good reason to avoid faking kicks or running reverses. Here’s an analogy. In blackjack, it feels uncomfortable to hit on 16. You frequently bust and feel stupid. However, it’s almost always the mathematically best play because the dealer will often beat 16. Often you’re simply giving the house extra edge when you stay on 16. Like with hitting on 16, faking a punt on your own side of the field and failing probably feels stupid. However, it’s mathematically advantageous. There’s plenty of room to try it more than 1% of the time. Similarly, I think it’s an important point that all of these trick plays have high standard deviation. That suggests that, even if the EPA of those plays is the same as a normal play, sometimes when a team is overmatched it’d still be advantageous to try them. If you’re up to an 80% win probability, game theory says don’t try a bunch of crazy plays that might immediately reverse that win probability. For the same reason, teams intelligently run more often when they are far ahead. On the flip side, if you’re sitting on a 30–40% win probability, a fake punt or field goal might be the type of play your team needs to jump to a 55% win probability. Let’s see what teams actually do: Average Win Prob at time of punt attempt: 0.462Average Win Prob at time of fake punt attempt: 0.398Average Win Prob at time of field goal attempt: 0.578Average Win Prob at time of fake field goal attempt: 0.561Average Win Prob at time of run attempt: 0.559Average Win Prob at time of trick run attempt: 0.534Average Win Prob at time of pass attempt: 0.490Average Win Prob at time of trick pass attempt: 0.557 It seems that teams are only correctly using fake punts when they are in a tough situation. Field Goals, trick passes, and trick runs are all only being run while the teams are (on average) ahead already. That is suboptimal, and probably due to coaches being too conservative. Of course, all this being said, there are certain trick plays that are never optimal to run: This article has been kicking around in my brain ever since I saw an impressive Mohamed Sanu stat line. I’m going to be sure to give a shout out. On 8 attempts when Sanu passes the ball, he’s on average added 2 points a play! That’s insane! Here are those 8 passes: (14:53) (Shotgun) Direct snap to M.Sanu. M.Sanu pass deep middle to A.Green for 73 yards, TOUCHDOWN.(12:48) M.Sanu pass deep right to G.Bernard pushed ob at CLE 9 for 25 yards (B.Mingo). {Ball lateraled from Dalton to Sanu} Cleveland challenged the pass completion ruling, and the play was Upheld. (Timeout #2.)(1:03) M.Sanu pass deep right to B.Tate pushed ob at ATL 24 for 50 yards (D.Lowery).(:06) (Shotgun) M.Sanu pass short left to A.Dalton for 18 yards, TOUCHDOWN. {Dalton pitched out to Sanu, who then passed to Dalton.}(3:28) (Shotgun) M.Sanu pass short right to A.Green to TB 27 for 11 yards (B.McDougald). #14 lateral to #12(12:44) Direct snap to M.Sanu. M.Sanu pass deep left to Ju.Jones for 51 yards, TOUCHDOWN.(8:56) T.Sambrailo reported in as eligible. Direct snap to M.Sanu. M.Sanu pass incomplete deep left to J.Jones.(8:55) (Shotgun) M.Sanu pass short right to M.Ryan for 5 yards, TOUCHDOWN. So, there are other variables at play. If one of your wide receivers has a golden deep ball then it makes the math easier. The video makes it even more impressive: To conclude, NFL teams should run trick plays more often*. If nothing else, it’s fun. Code can be found here. *depending on many factors
[ { "code": null, "e": 1002, "s": 172, "text": "Trick plays in football are one of the most fun parts of the game. Double reverses, fake field goals, and flea flickers usually make highlight reels. They are high variance in nature: either you catch the defense off guard and score an easy touchdown, or you have your running back throw a duck into double coverage and give the other team the ball on a silver platter. The high-variance nature of trick plays is intuitive to anyone who watches a lot of football. What might not be intuitive is their actual value. Until recently, the data required to objectively evaluate trick plays was not easily accessible to the public. Thanks to great work by Ron Yurko, and great tutorials by Ben Baldwin and Github user @Deryck97, any schmuck such as myself can spend a couple hours analyzing the value goofy plays over a 10 year period." }, { "code": null, "e": 1908, "s": 1002, "text": "How do you capture the value of a play? Obviously a 50-yard completion is worth more than a 2 yard run in almost all cases. However, is a 4 yard run on first down worth more than a 1 yard 3rd down conversion? That’s a difficult question to precisely answer. It’s clear however that not all yards are created equal. A screen pass to end the half against prevent defense might rack up 30 yards as time runs out. All that does is pad stats. Any NFL coach would rather have a 3rd down conversion in a key situation no matter how short. Ron Yurko authored a paper detailing an Expected Points Added metric. In the paper (found here), he is able to determine the amount of points a team is expected to score from any point during the game. If, after a play, that expected points metric is higher, then the play added expected points. Of course, a play such as a sack or interception will result in negative EPA." }, { "code": null, "e": 2057, "s": 1908, "text": "Obviously, 90+ yard offensive plays will have the highest EPA and Redzone turnovers have the worst EPA. Here are the top 5 EPA plays in the dataset:" }, { "code": null, "e": 2633, "s": 2057, "text": "Description (3:15) (Shotgun) B.Roethlisberger pass deep middle to J.Smith-Schuster for 97 yards, TOUCHDOWN. EPA 9.5Description (10:06) (Shotgun) C.Johnson up the middle for 91 yards, TOUCHDOWN. EPA 9.3Description (7:44) (Shotgun) C.Palmer pass short middle to M.Floyd for 91 yards, TOUCHDOWN. EPA 9.2Description (8:51) (Shotgun) P.Mahomes pass deep middle to D.Robinson for 89 yards, TOUCHDOWN. PENALTY on KC-D.Robinson, Taunting, 15 yards, enforced between downs. EPA 9.1Description (11:51) (Shotgun) D.Carr pass deep middle to A.Cooper for 87 yards, TOUCHDOWN. EPA 8.9" }, { "code": null, "e": 2674, "s": 2633, "text": "You get the idea. Here are the bottom 5:" }, { "code": null, "e": 3795, "s": 2674, "text": "Description (12:14) (No Huddle, Shotgun) M.Vick to WAS 10 for -6 yards (R.Kerrigan). FUMBLES (R.Kerrigan), touched at WAS 10, RECOVERED by WAS-D.Hall at WAS 25. D.Hall for 75 yards, TOUCHDOWN. Lateral batted by 91 - Kerrigan The Replay Assistant challenged the backward pass ruling, and the play was Upheld. EPA -12.8Description (11:14) (Shotgun) J.Tuel pass short right intended for T.Graham INTERCEPTED by S.Smith at KC 0. S.Smith for 100 yards, TOUCHDOWN. EPA -12.7Description (6:05) (Shotgun) M.Cassel sacked at DEN 25 for -17 yards (M.Haggan). FUMBLES (M.Haggan), RECOVERED by DEN-J.Hunter at DEN 25. J.Hunter for 75 yards, TOUCHDOWN. EPA -12.1Description (2:51) M.Vick pass short left intended for B.Celek INTERCEPTED by P.Robinson at NO 1. P.Robinson for 99 yards, TOUCHDOWN. PENALTY on PHI-M.Vick, Low Block, 15 yards, enforced between downs. The penalty for a low block during the interception return will be assessed on the ensuing kickoff. EPA -12.1Description (7:50) (Shotgun) E.Manning pass short left intended for H.Nicks INTERCEPTED by B.McCann at DAL -1. B.McCann for 101 yards, TOUCHDOWN. EPA -12.1" }, { "code": null, "e": 4303, "s": 3795, "text": "EPA is a funny thing, since on offense it can be greater than a touchdown. That makes sense, because if you’re backed up against your own endzone, you’re expected 1) not to score on the drive and 2) the other team is more likely to score on their next drive because of the short field. It can also be -12, because in the redzone 1) you’re expected to score around 5 points on average, and 2) the next possession for the defensive team is supposed to be post-kickoff, probably on their own half of the field." }, { "code": null, "e": 4524, "s": 4303, "text": "Now that we have a metric for the value of a play, we can start grouping types of plays together and comparing them. For example, taken from @Deryck97’s tutorial linked above, a comparison of rush vs. pass plays in 2018:" }, { "code": null, "e": 4730, "s": 4524, "text": "So, using nflscrapR data, how do we know if a play is a trick play? Unfortunately there’s no easy indicator variable that says ‘trick play’. Instead, we have to come up with creative ways to identify them." }, { "code": null, "e": 5124, "s": 4730, "text": "The easiest plays to start with are fake kicks. Most play descriptions contain the formation of the play. If a play is labeled ‘Punt formation’ or ‘Field Goal formation’, yet the play type is a run or a pass, then it is likely to be a fake. I had to manually filter some other play types, like when the punter muffs a snap and aborts the play, but that was pretty easy. Here’s the python code:" }, { "code": null, "e": 5779, "s": 5124, "text": "punts = df.loc[df.desc.str.contains('punt|Punt')]fake_punts = punts.loc[(punts['play_type']=='run')|(punts['play_type']=='pass')]# drop enforced penaltiesfake_punts = fake_punts.loc[fake_punts.penalty!=1]# drop non enforced penaltiesfake_punts =fake_punts.loc[~fake_punts.desc.str.contains('Penalty')]# drop punter mishandles fake_punts=fake_punts.loc[~fake_punts.desc.str.contains('Aborted|Shotgun')] # drop plays where punter intentionally runs out of end zone (not likely to fake a punt in own redzone)fake_punts = fake_punts.loc[~fake_punts.desc.str.contains('SAFETY')] # drop plays without descriptionfake_punts.dropna(subset=['desc'], inplace=True)" }, { "code": null, "e": 6009, "s": 5779, "text": "I then apply the same filters to plays that did end in an actual punt. There ended up being 177 instances of fakes that I could pick up out of about 22,000 punt attempts (regular season and playoffs). A fake rate of less than 1%!" }, { "code": null, "e": 6198, "s": 6009, "text": "Let’s come up with some baselines as well. I’ll show the average EPA of a punt, the average EPA of a pass play, the average EPA of a run play, and the average EPA of a pass by Tom Brady 🐐." }, { "code": null, "e": 6519, "s": 6198, "text": "Wow! Fake punts are worth about seven times as much as a Tom Brady pass. Of course, the standard deviation of the EPA is much higher too. The standard deviation of the EPA of non-fake punts were 1.16, while the standard deviation of fake punts was 3.17. Obviously, if you fail a fake, then you have a large negative EPA." }, { "code": null, "e": 7232, "s": 6519, "text": "Are fake field goals just as valuable? According to my simple analysis, no. Throwing out fumbles, bad snaps, penalties, etc — the EPA of a fake field goal is 0.06. That’s higher than your average pass, but not super exciting since I ran it after the fake punt numbers. I believe this is because what you’re giving up by forgoing a field goal. If you fail a fake field goal, you lose a few expected points you would’ve gotten from the attempt. If all you’re doing is getting a first down, you’re not even gaining that many expected points. They have a similarly large standard deviation like the fake punts. So if you’re trailing a few points, you still might be better off rolling the dice and going with a fake." }, { "code": null, "e": 7571, "s": 7232, "text": "Trick run plays and pass plays are not as easy to isolate unfortunately. As a disclaimer, the point this article was to start playing with the NFL play-by-play data. I’m not writing a dissertation on fake plays. So while I did go to lengths to isolate trick plays successfully, I’m not claiming 100% accuracy or the best possible process." }, { "code": null, "e": 7906, "s": 7571, "text": "Let’s start with passes. I began by throwing out obvious plays (penalties, two-point conversion attempts) as well as plays I’ve already analyzed (kick formations). I also threw out plays with extreme win probabilities (<5% & >95% win probability). The idea there is to avoid desperate late-game lateral plays like the hook and latter." }, { "code": null, "e": 8389, "s": 7906, "text": "I then searched play descriptions for flea flickers and passes by players with less than 30 attempts in the data set. Flea flickers cover laterals to the QB, and in theory, any other trick pass would involve a lateral to a running back or wide receiver that doesn’t normally pass it. Finally, I black-listed QBs that only came in for a very brief period of time and were picked up by my filters. They were easy to find because a whole series of plays sticks out in the descriptions." }, { "code": null, "e": 8755, "s": 8389, "text": "Almost there. For run plays, I isolated plays that had a description of lateral or reverse. Luckily, there weren’t many cases of defensive players lateraling after a fumble recovery. I ended up with a sample of 180 plays (manually removed a weird one or two). I made the choice to exclude two-point conversion attempts, so unfortunately this beauty wasn’t included:" }, { "code": null, "e": 8783, "s": 8755, "text": "Whew. Here are the results:" }, { "code": null, "e": 9409, "s": 8783, "text": "I was surprised to find that reverses and lateral run plays were so valuable! In theory, they’re like having a player twice as good as Tom Brady passing the ball. Since running plays aren’t usually as valuable as passing plays, I expected trick passes to have higher EPA. Trick passes are still valuable, but a lot of the EPA was driven by flea-flickers alone. In fact, only counting running back and WR passes (n=194), the EPA was 0.024 — worse than a normal pass! Flea-flickers, when only grouped by themselves (n=66), had an EPA of 0.3 — very valuable. I guess the risk of your non-QB throwing an interception is too high." }, { "code": null, "e": 9690, "s": 9409, "text": "Of course, if a team fakes punts all the time then defenses will adjust and the EPA will go down. The appropriate criticism here is that the novelty of the play is what makes them valuable. Still, my analysis suggests that teams should definitely run more reverses and fake punts." }, { "code": null, "e": 10080, "s": 9690, "text": "On a different note, I would argue that risk tolerance isn’t a good reason to avoid faking kicks or running reverses. Here’s an analogy. In blackjack, it feels uncomfortable to hit on 16. You frequently bust and feel stupid. However, it’s almost always the mathematically best play because the dealer will often beat 16. Often you’re simply giving the house extra edge when you stay on 16." }, { "code": null, "e": 10286, "s": 10080, "text": "Like with hitting on 16, faking a punt on your own side of the field and failing probably feels stupid. However, it’s mathematically advantageous. There’s plenty of room to try it more than 1% of the time." }, { "code": null, "e": 10972, "s": 10286, "text": "Similarly, I think it’s an important point that all of these trick plays have high standard deviation. That suggests that, even if the EPA of those plays is the same as a normal play, sometimes when a team is overmatched it’d still be advantageous to try them. If you’re up to an 80% win probability, game theory says don’t try a bunch of crazy plays that might immediately reverse that win probability. For the same reason, teams intelligently run more often when they are far ahead. On the flip side, if you’re sitting on a 30–40% win probability, a fake punt or field goal might be the type of play your team needs to jump to a 55% win probability. Let’s see what teams actually do:" }, { "code": null, "e": 11381, "s": 10972, "text": "Average Win Prob at time of punt attempt: 0.462Average Win Prob at time of fake punt attempt: 0.398Average Win Prob at time of field goal attempt: 0.578Average Win Prob at time of fake field goal attempt: 0.561Average Win Prob at time of run attempt: 0.559Average Win Prob at time of trick run attempt: 0.534Average Win Prob at time of pass attempt: 0.490Average Win Prob at time of trick pass attempt: 0.557" }, { "code": null, "e": 11658, "s": 11381, "text": "It seems that teams are only correctly using fake punts when they are in a tough situation. Field Goals, trick passes, and trick runs are all only being run while the teams are (on average) ahead already. That is suboptimal, and probably due to coaches being too conservative." }, { "code": null, "e": 11751, "s": 11658, "text": "Of course, all this being said, there are certain trick plays that are never optimal to run:" }, { "code": null, "e": 12017, "s": 11751, "text": "This article has been kicking around in my brain ever since I saw an impressive Mohamed Sanu stat line. I’m going to be sure to give a shout out. On 8 attempts when Sanu passes the ball, he’s on average added 2 points a play! That’s insane! Here are those 8 passes:" }, { "code": null, "e": 12929, "s": 12017, "text": "(14:53) (Shotgun) Direct snap to M.Sanu. M.Sanu pass deep middle to A.Green for 73 yards, TOUCHDOWN.(12:48) M.Sanu pass deep right to G.Bernard pushed ob at CLE 9 for 25 yards (B.Mingo). {Ball lateraled from Dalton to Sanu} Cleveland challenged the pass completion ruling, and the play was Upheld. (Timeout #2.)(1:03) M.Sanu pass deep right to B.Tate pushed ob at ATL 24 for 50 yards (D.Lowery).(:06) (Shotgun) M.Sanu pass short left to A.Dalton for 18 yards, TOUCHDOWN. {Dalton pitched out to Sanu, who then passed to Dalton.}(3:28) (Shotgun) M.Sanu pass short right to A.Green to TB 27 for 11 yards (B.McDougald). #14 lateral to #12(12:44) Direct snap to M.Sanu. M.Sanu pass deep left to Ju.Jones for 51 yards, TOUCHDOWN.(8:56) T.Sambrailo reported in as eligible. Direct snap to M.Sanu. M.Sanu pass incomplete deep left to J.Jones.(8:55) (Shotgun) M.Sanu pass short right to M.Ryan for 5 yards, TOUCHDOWN." }, { "code": null, "e": 13093, "s": 12929, "text": "So, there are other variables at play. If one of your wide receivers has a golden deep ball then it makes the math easier. The video makes it even more impressive:" }, { "code": null, "e": 13203, "s": 13093, "text": "To conclude, NFL teams should run trick plays more often*. If nothing else, it’s fun. Code can be found here." } ]
Powershell - ForEach Loop
The following scripts demonstrates the ForEach loop. > $array = @("item1", "item2", "item3") > foreach ($element in $array) { $element } item1 item2 item3 > $array | foreach { $_ } item1 item2 item3 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2087, "s": 2034, "text": "The following scripts demonstrates the ForEach loop." }, { "code": null, "e": 2237, "s": 2087, "text": "> $array = @(\"item1\", \"item2\", \"item3\")\n \n> foreach ($element in $array) { $element }\nitem1\nitem2\nitem3\n \n> $array | foreach { $_ }\nitem1\nitem2\nitem3" }, { "code": null, "e": 2272, "s": 2237, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2293, "s": 2272, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2328, "s": 2293, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2341, "s": 2328, "text": " Vijay Saini" }, { "code": null, "e": 2378, "s": 2341, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2390, "s": 2378, "text": " Fettah Ben" }, { "code": null, "e": 2397, "s": 2390, "text": " Print" }, { "code": null, "e": 2408, "s": 2397, "text": " Add Notes" } ]
Python | Functions | Question 4 - GeeksforGeeks
18 Jan, 2021 What is the output of the following program : y = 8z = lambda x : x * yprint (z(6)) (A) 48(B) 14(C) 64(D) None of the aboveAnswer: (A)Explanation: lambdas are concise functions and thus, result = 6 * 8Quiz of this Question jadhavhitesh207 Functions Python-Functions Python-Quizzes Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python-Quizzes | Python List Quiz | Question 5 Python-Quizzes | Python List Quiz | Question 4 Python-Quizzes | Python Dictionary Quiz | Question 25 Python-Quizzes | Python Dictionary Quiz | Question 23 Output of Python Program - Dictionary (set 25) Python | Output Type | Question 1 Why do people prefer Selenium with Python? Python | Output Type | Question 3 Python | Animated Banner showing 'GeeksForGeeks' Python-Quizzes | Output Type | Question 10
[ { "code": null, "e": 24051, "s": 24023, "text": "\n18 Jan, 2021" }, { "code": null, "e": 24097, "s": 24051, "text": "What is the output of the following program :" }, { "code": "y = 8z = lambda x : x * yprint (z(6))", "e": 24135, "s": 24097, "text": null }, { "code": null, "e": 24274, "s": 24135, "text": "(A) 48(B) 14(C) 64(D) None of the aboveAnswer: (A)Explanation: lambdas are concise functions and thus, result = 6 * 8Quiz of this Question" }, { "code": null, "e": 24290, "s": 24274, "text": "jadhavhitesh207" }, { "code": null, "e": 24300, "s": 24290, "text": "Functions" }, { "code": null, "e": 24317, "s": 24300, "text": "Python-Functions" }, { "code": null, "e": 24332, "s": 24317, "text": "Python-Quizzes" }, { "code": null, "e": 24342, "s": 24332, "text": "Functions" }, { "code": null, "e": 24440, "s": 24342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24487, "s": 24440, "text": "Python-Quizzes | Python List Quiz | Question 5" }, { "code": null, "e": 24534, "s": 24487, "text": "Python-Quizzes | Python List Quiz | Question 4" }, { "code": null, "e": 24588, "s": 24534, "text": "Python-Quizzes | Python Dictionary Quiz | Question 25" }, { "code": null, "e": 24642, "s": 24588, "text": "Python-Quizzes | Python Dictionary Quiz | Question 23" }, { "code": null, "e": 24689, "s": 24642, "text": "Output of Python Program - Dictionary (set 25)" }, { "code": null, "e": 24723, "s": 24689, "text": "Python | Output Type | Question 1" }, { "code": null, "e": 24766, "s": 24723, "text": "Why do people prefer Selenium with Python?" }, { "code": null, "e": 24800, "s": 24766, "text": "Python | Output Type | Question 3" }, { "code": null, "e": 24849, "s": 24800, "text": "Python | Animated Banner showing 'GeeksForGeeks'" } ]
How to Change the ProgressBar Color in Android? - GeeksforGeeks
23 Feb, 2021 In this article, we will see how we can add color to a ProgressBar in android. Android ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the ProgressBar estimate the time remaining in operation. Note in this article we will be using Java and XML to set the color. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Create a custom ProgressBar Go to the app > res > drawable > right-click > New > Drawable Resource File and name the file as progress_bg. Inside the XML file add a rotate tag with some attributes(see code) Inside rotate tag create a shape tag within which create the size and gradient tag Attributes of these tags are given in the code below. Below is the code for the progress_bg.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--use rotate tag to rotate the drawable--><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="360"> <!--shape tag is used to build a shape in XML--> <shape android:innerRadiusRatio="3" android:shape="ring" android:thicknessRatio="8" android:useLevel="false"> <!--set the size of the shape--> <size android:width="76dip" android:height="76dip" /> <!--set the color gradients of the shape--> <gradient android:angle="0" android:endColor="#00ffffff" android:startColor="#447a29" android:type="sweep" android:useLevel="false" /> </shape> </rotate> Step 3: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Open the activity_main.xml file and in the ProgressBar tag and set the drawable in indeterminateDrawable attribute. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp"> <!--set the custom progress bar here in the indeterminateDrawable attribute--> <ProgressBar android:id="@+id/ProgressBar01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:indeterminate="true" android:indeterminateDrawable="@drawable/progress_bg" android:progress="0" /> <Button android:id="@+id/show_button" android:layout_width="191dp" android:layout_height="wrap_content" android:layout_below="@id/ProgressBar01" android:layout_centerHorizontal="true" android:layout_marginTop="80dp" android:text="Progress Bar" /> </RelativeLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.os.Handler;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Handler handler = new Handler(); public static Button button; public static TextView textView; public static ImageView img1, img2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a progress bar variable and set the id final ProgressBar progressBar = findViewById(R.id.ProgressBar01); // show the progress bar progressBar.getProgress(); }} Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example Android Listview in Java with Example How to Read Data from SQLite Database in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25492, "s": 25116, "text": "In this article, we will see how we can add color to a ProgressBar in android. Android ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the ProgressBar estimate the time remaining in operation. Note in this article we will be using Java and XML to set the color." }, { "code": null, "e": 25521, "s": 25492, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25633, "s": 25521, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. " }, { "code": null, "e": 25684, "s": 25633, "text": "Note that select Java as the programming language." }, { "code": null, "e": 25720, "s": 25684, "text": "Step 2: Create a custom ProgressBar" }, { "code": null, "e": 25830, "s": 25720, "text": "Go to the app > res > drawable > right-click > New > Drawable Resource File and name the file as progress_bg." }, { "code": null, "e": 25898, "s": 25830, "text": "Inside the XML file add a rotate tag with some attributes(see code)" }, { "code": null, "e": 25981, "s": 25898, "text": "Inside rotate tag create a shape tag within which create the size and gradient tag" }, { "code": null, "e": 26036, "s": 25981, "text": "Attributes of these tags are given in the code below. " }, { "code": null, "e": 26085, "s": 26036, "text": "Below is the code for the progress_bg.xml file. " }, { "code": null, "e": 26089, "s": 26085, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--use rotate tag to rotate the drawable--><rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fromDegrees=\"0\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:toDegrees=\"360\"> <!--shape tag is used to build a shape in XML--> <shape android:innerRadiusRatio=\"3\" android:shape=\"ring\" android:thicknessRatio=\"8\" android:useLevel=\"false\"> <!--set the size of the shape--> <size android:width=\"76dip\" android:height=\"76dip\" /> <!--set the color gradients of the shape--> <gradient android:angle=\"0\" android:endColor=\"#00ffffff\" android:startColor=\"#447a29\" android:type=\"sweep\" android:useLevel=\"false\" /> </shape> </rotate>", "e": 26957, "s": 26089, "text": null }, { "code": null, "e": 27005, "s": 26957, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 27072, "s": 27005, "text": "Go to the activity_main.xml file and refer to the following code. " }, { "code": null, "e": 27189, "s": 27072, "text": "Open the activity_main.xml file and in the ProgressBar tag and set the drawable in indeterminateDrawable attribute. " }, { "code": null, "e": 27239, "s": 27189, "text": "Below is the code for the activity_main.xml file." }, { "code": null, "e": 27243, "s": 27239, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"20dp\"> <!--set the custom progress bar here in the indeterminateDrawable attribute--> <ProgressBar android:id=\"@+id/ProgressBar01\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:indeterminate=\"true\" android:indeterminateDrawable=\"@drawable/progress_bg\" android:progress=\"0\" /> <Button android:id=\"@+id/show_button\" android:layout_width=\"191dp\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/ProgressBar01\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"80dp\" android:text=\"Progress Bar\" /> </RelativeLayout>", "e": 28191, "s": 27243, "text": null }, { "code": null, "e": 28239, "s": 28191, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 28306, "s": 28239, "text": "Go to the MainActivity.java file and refer to the following code. " }, { "code": null, "e": 28430, "s": 28306, "text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28435, "s": 28430, "text": "Java" }, { "code": "import android.os.Bundle;import android.os.Handler;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Handler handler = new Handler(); public static Button button; public static TextView textView; public static ImageView img1, img2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a progress bar variable and set the id final ProgressBar progressBar = findViewById(R.id.ProgressBar01); // show the progress bar progressBar.getProgress(); }}", "e": 29249, "s": 28435, "text": null }, { "code": null, "e": 29262, "s": 29249, "text": "Android-Bars" }, { "code": null, "e": 29270, "s": 29262, "text": "Android" }, { "code": null, "e": 29275, "s": 29270, "text": "Java" }, { "code": null, "e": 29280, "s": 29275, "text": "Java" }, { "code": null, "e": 29288, "s": 29280, "text": "Android" }, { "code": null, "e": 29386, "s": 29288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29395, "s": 29386, "text": "Comments" }, { "code": null, "e": 29408, "s": 29395, "text": "Old Comments" }, { "code": null, "e": 29447, "s": 29408, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29489, "s": 29447, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29522, "s": 29489, "text": "GridView in Android with Example" }, { "code": null, "e": 29560, "s": 29522, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29610, "s": 29560, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29625, "s": 29610, "text": "Arrays in Java" }, { "code": null, "e": 29669, "s": 29625, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29691, "s": 29669, "text": "For-each loop in Java" }, { "code": null, "e": 29727, "s": 29691, "text": "Arrays.sort() in Java with examples" } ]
How to embed Bootstrap CSS & JS in your Python Dash app | by Mauro Di Pietro | Towards Data Science
In this article I will show how to build a web app that forecasts the spread of covid-19 virus within any infected countries using Python, Dash and Bootstrap, that looks like this: Let me start with this: coding a Dash app is messy... I don’t mean any harm with this, I like Dash and I think it is the future of web development for Python. Dash is a Python (and R) framework for building web applications. It’s built on top of Flask, Plotly.js and React js. It is open source, its apps run on the web browser. Dash is super convenient if you are better in Python than Javascript because allows you to build dashboards using pure Python. I don’t know if you’ve ever seen a dash application code. It’s a mess: the code comes out really long as you need to write every html Div with contents and properties, just like an html page before that Bootstrap was invented. Bootstrap is an open source toolkit for developing with HTML, CSS, and JS. It is the most used library for web development thanks to its extensive prebuilt components and powerful plugins built on jQuery. I love Boostrap, not only because the output is always pretty good looking, but especially because it saves you lines and lines of HTML, CSS and JS code. What if I tell you that it is possible also for Dash applications? You like the sound of that, don’t you? Through this tutorial I will explain step by step how Bootstrap can be easily integrated in Dash and how to build and deploy a web application, using my Covid-19 infection forecaster app as an example (link below, it might take 30 seconds to load). app-virus-forecaster.herokuapp.com I will present some useful Python code that can be easily used in other similar cases (just copy, paste, run) and walk through every line of code with comments, so that you can easily replicate this example (link to the full code below). github.com I’ll use the most popular dataset in these days of quarantine: CSSE COVID-19 dataset. It presents the time series of the number of confirmed cases of contagion reported by each country every day since the pandemic started. This dataset is freely available on the GitHub of the Johns Hopkins University (link below). github.com In particular, I will go through: Setup of the environment Back-end: Write the model to get, process and plot the data Front-end: Build the app with Dash and Bootstrap Deploy the app First of all, I will install the following libraries through the terminal: pip install dashpip install dash-bootstrap-componentspip install pandas The command to install dash will also download useful packages like dash-core-components, dash-html-components and plotly. Similarly, pandas installation includes numpy and scipy that I will use later as well. I assume you already know those, therefore I shall take a moment to introduce Dash Bootstrap Components: basically it’s what does the trick to integrate Bootstrap in Dash and makes easier to build consistently styled apps with complex and responsive layouts. I’m a fan of this library because it saves a huge number of lines of dash code, you’ll see later. After installing all you need, I would recommend running the following command on the terminal to save the requirements on the appropriate text file: pip freeze > requirements.txt In regard to the folder structure, I put 4 fundamental elements on root level: application folder: where all the dash code is going to be, in dash.py file python folder: where I place the logic of the model settings folder: where there are all the configurations run.py file: that runs the whole thing if executed on the terminal with the following command python run.py Those mentioned so far are all I need to make the app work, however, there are some other useful but unnecessary things that I added like static images (in application folder), comments (in settings folder), Procfile and requirements.txt used in deployment (on root level). To summarize, the app shall have the following structure: Now that it’s all set, I will go through each python file and show the code in it. Let’s get started, shall we? Firstly, I will write the class to get Covid-19 infection data, then I will build the model that learns from past observation and forecast the future trend of the time series. In data.py (inside the python folder) I’ll define the “Data” class with a method that shall be executed when the app starts, meaning that every time the page of the browser where the app runs is loaded, the back-end gets fresh data directly from the source (“get_data” function in the code below). It’s important to save the list of countries because it will be shown to users on the dashboard for selecting a specific country. The Data class has also the task to receive the input from the front-end, the country selected by the user, filter and process data (“process_data” function in the code below). Before filtering for a specific country, I’d create an aggregated time series called “World” which shall be the default selected country when the app starts. In python terms, the data.py file looks like this: import pandas as pdclass Data(): def get_data(self): self.dtf_cases = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv", sep=",") self.countrylist = ["World"] + self.dtf_cases["Country/Region"].unique().tolist() @staticmethod def group_by_country(dtf, country): dtf = dtf.drop(['Province/State','Lat','Long'], axis=1).groupby("Country/Region").sum().T dtf["World"] = dtf.sum(axis=1) dtf = dtf[country] dtf.index = pd.to_datetime(dtf.index, infer_datetime_format=True) ts = pd.DataFrame(index=dtf.index, data=dtf.values, columns=["data"]) return ts def process_data(self, country): self.dtf = self.group_by_country(self.dtf_cases, country) Now, I’ll build the model to fit data and forecast. The purpose of this article is not to dig in what is the most appropriate model for this dataset, therefore I’ll keep it simple: I am going to use a parametric curve fitting approach, optimizing the parameters of a logistic function for each country time series. If you are interested in this basic modelling approach you can find it explained here. In model.py (inside the python folder) I’ll define the “Model” class with a method (“forecast” function in the code below) that shall be executed on the World time series when the app starts and each time that a specific country is selected from the front-end. This class has the job to fit the best logistic function on the selected country data (with scipy) and produce a pandas dataframe with: the actual data and the fitted logistic model, which shall be used to plot the total cases the daily change of the actual data and the fitted logistic model (delta t = y t — y t-1), which shall be used to plot the active cases. To give an illustration, the model.py file contains the following code: import pandas as pdimport numpy as npfrom scipy import optimizeclass Model(): def __init__(self, dtf): self.dtf = dtf @staticmethod def f(X, c, k, m): y = c / (1 + np.exp(-k*(X-m))) return y @staticmethod def fit_parametric(X, y, f, p0): model, cov = optimize.curve_fit(f, X, y, maxfev=10000, p0=p0) return model @staticmethod def forecast_parametric(model, f, X): preds = f(X, model[0], model[1], model[2]) return preds @staticmethod def generate_indexdate(start): index = pd.date_range(start=start, periods=30, freq="D") index = index[1:] return index @staticmethod def add_diff(dtf): ## create delta columns dtf["delta_data"] = dtf["data"] - dtf["data"].shift(1) dtf["delta_forecast"] = dtf["forecast"] - dtf["forecast"].shift(1) ## fill Nas dtf["delta_data"] = dtf["delta_data"].fillna(method='bfill') dtf["delta_forecast"] = dtf["delta_forecast"].fillna(method='bfill') ## interpolate outlier idx = dtf[pd.isnull(dtf["data"])]["delta_forecast"].index[0] posx = dtf.index.tolist().index(idx) posx_a = posx - 1 posx_b = posx + 1 dtf["delta_forecast"].iloc[posx] = (dtf["delta_forecast"].iloc[posx_a] + dtf["delta_forecast"].iloc[posx_b])/2 return dtf def forecast(self): ## fit y = self.dtf["data"].values t = np.arange(len(y)) model = self.fit_parametric(t, y, self.f, p0=[np.max(y),1,1]) fitted = self.f(t, model[0], model[1], model[2]) self.dtf["forecast"] = fitted ## forecast t_ahead = np.arange(len(y)+1, len(y)+30) forecast = self.forecast_parametric(model, self.f, t_ahead) ## create dtf self.today = self.dtf.index[-1] idxdates = self.generate_indexdate(start=self.today) preds = pd.DataFrame(data=forecast, index=idxdates, columns=["forecast"]) self.dtf = self.dtf.append(preds) ## add diff self.dtf = self.add_diff(self.dtf) It’s time to make some cool plots and the best tool for the job is Plotly as Dash is built on top of it. I will put in result.py (inside the python folder) the class that is going to take care of this with the method to plot the total cases time series and its forecast (“plot_total” function in the code below): the method to plot the active cases time series and its forecast (“plot_active” function in the code below): the method to retrieve some statistics to show on the front-end (“get_panel” function in the code below): Here’s the code full code in result.py: import pandas as pdimport plotly.graph_objects as goclass Result(): def __init__(self, dtf): self.dtf = dtf @staticmethod def calculate_peak(dtf): data_max = dtf["delta_data"].max() forecast_max = dtf["delta_forecast"].max() if data_max >= forecast_max: peak_day = dtf[dtf["delta_data"]==data_max].index[0] return peak_day, data_max else: peak_day = dtf[dtf["delta_forecast"]==forecast_max].index[0] return peak_day, forecast_max @staticmethod def calculate_max(dtf): total_cases_until_today = dtf["data"].max() total_cases_in_30days = dtf["forecast"].max() active_cases_today = dtf["delta_data"].max() active_cases_in_30days = dtf["delta_forecast"].max() return total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days def plot_total(self, today): ## main plots fig = go.Figure() fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf["data"], mode='markers', name='data', line={"color":"black"})) fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf["forecast"], mode='none', name='forecast', fill='tozeroy')) ## add slider fig.update_xaxes(rangeslider_visible=True) ## set background color fig.update_layout(plot_bgcolor='white', autosize=False, width=1000, height=550) ## add vline fig.add_shape({"x0":today, "x1":today, "y0":0, "y1":self.dtf["forecast"].max(), "type":"line", "line":{"width":2,"dash":"dot"} }) fig.add_trace(go.Scatter(x=[today], y=[self.dtf["forecast"].max()], text=["today"], mode="text", line={"color":"green"}, showlegend=False)) return fig def plot_active(self, today): ## main plots fig = go.Figure() fig.add_trace(go.Bar(x=self.dtf.index, y=self.dtf["delta_data"], name='data', marker_color='black')) fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf["delta_forecast"], mode='none', name='forecast', fill='tozeroy')) ## add slider fig.update_xaxes(rangeslider_visible=True) ## set background color fig.update_layout(plot_bgcolor='white', autosize=False, width=1000, height=550) ## add vline fig.add_shape({"x0":today, "x1":today, "y0":0, "y1":self.dtf["delta_forecast"].max(), "type":"line", "line":{"width":2,"dash":"dot"} }) fig.add_trace(go.Scatter(x=[today], y=[self.dtf["delta_forecast"].max()], text=["today"], mode="text", line={"color":"green"}, showlegend=False)) return fig def get_panel(self): peak_day, num_max = self.calculate_peak(self.dtf) total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days = self.calculate_max(self.dtf) return peak_day, num_max, total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days Finally, here we are, about to code the app using Dash and Dash Bootstrap Components (henceforth as “dbc”), I am going to explain it step by step and also provide the full code of dash.py (inside the application folder). For this we need the following imports: import dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbc As start, I need to define the app instance and in doing this dbc already provides a great feature in choosing a Bootstrap CSS theme: app = dash.Dash(external_stylesheets=[dbc.themes.LUX]) Following a visual order, I shall now approach the top navbar. I want something cool and reactive on click, with pop-ups and a drop-down menu, but I’d like to not waste too much time on writing CSS and JS code. To put it another way, I want to use Bootstrap like this: Similarly to this html, we can use dbc to crate the navbar and its items: dbc.Nav([ dbc.NavItem(), dbc.NavItem(), dbc.DropdownMenu()]) You got the gimmick, right? Dash and Dbc replicate the same structure and logic of the html syntax. With this in mind, inside each item we can add whatever we want: Moving on with the input form, I‘d like to get a simple drop-down menu with all the possible countries as options and the “World” as default selection. In order to do this, it’s necessary to read the data before coding the drop-down menu object. Do you remember the Data class written before in data.py (python folder)? Well, now it’s the right time to use it: from python.data import Datadata = Data()data.get_data() Now that we have the country list in the Data object, we can write the drop-down menu and set the options in it with a simple for loop: dcc.Dropdown(id="country", options=[{"label":x,"value":x} for x in data.countrylist], value="World")]) In Dash, if not specifically programmed, the output will be put in rows, one below the other. However, I’d like to have all contained in the screen size, so users do not need to scroll down. That’s why I am going to use tabs and each one will show one of the 2 plots I coded before in result.py (in python folder) with plotly. With dbc this is super easy: dbc.Tabs([ dbc.Tab(dcc.Graph(id="plot-total"), label="Total cases"), dbc.Tab(dcc.Graph(id="plot-active"), label="Active cases") ]) I bet you’re wondering “how does the app know that in the first tab it has to put the first plot and in the second the other?”. Well, you’re not wrong, the app needs a link between the html and the Python code output. In Dash this is done with callbacks. A callback is nothing more than a decorator, a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Let’s take the plot of total cases as an example: I need a function that takes the country selected from the front-end as input and returns the plot as output using the Model and Result classes I coded before (in python folder). Something like this: def plot_total_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_total(model.today) As you surely noticed, in the previous code where I defined the tabs, I put an id in the first one (id=”plot-total”). So I need to add, on top of this function, a callback decorator to tell the app that the figure the back-end will plot refers to that id and that the input is the country value. @app.callback(output=Output("plot-total","figure"), inputs=[Input("country","value")]) Ultimately, the panel on the right with some statistics is a little different because the python function doesn’t return a plot like before but an entire html div. In fact, the dash code this time is going to be inside the callback function that calculate those numbers. I’m talking about this: This covers pretty much all the elements of the front-end layout, it’s a very basic application with one single input and few outputs (plots and numbers). Full code of dash.py: # Setupimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom settings import config, aboutfrom python.data import Datafrom python.model import Modelfrom python.result import Result# Read datadata = Data()data.get_data()# App Instanceapp = dash.Dash(name=config.name, assets_folder=config.root+"/application/static", external_stylesheets=[dbc.themes.LUX, config.fontawesome])app.title = config.name# Navbarnavbar = dbc.Nav(className="nav nav-pills", children=[ ## logo/home dbc.NavItem(html.Img(src=app.get_asset_url("logo.PNG"), height="40px")), ## about dbc.NavItem(html.Div([ dbc.NavLink("About", href="/", id="about-popover", active=False), dbc.Popover(id="about", is_open=False, target="about-popover", children=[ dbc.PopoverHeader("How it works"), dbc.PopoverBody(about.txt) ]) ])), ## links dbc.DropdownMenu(label="Links", nav=True, children=[ dbc.DropdownMenuItem([html.I(className="fa fa-linkedin"), " Contacts"], href=config.contacts, target="_blank"), dbc.DropdownMenuItem([html.I(className="fa fa-github"), " Code"], href=config.code, target="_blank") ])])# Inputinputs = dbc.FormGroup([ html.H4("Select Country"), dcc.Dropdown(id="country", options=[{"label":x,"value":x} for x in data.countrylist], value="World")])# App Layoutapp.layout = dbc.Container(fluid=True, children=[ ## Top html.H1(config.name, id="nav-pills"), navbar, html.Br(),html.Br(),html.Br(), ## Body dbc.Row([ ### input + panel dbc.Col(md=3, children=[ inputs, html.Br(),html.Br(),html.Br(), html.Div(id="output-panel") ]), ### plots dbc.Col(md=9, children=[ dbc.Col(html.H4("Forecast 30 days from today"), width={"size":6,"offset":3}), dbc.Tabs(className="nav nav-pills", children=[ dbc.Tab(dcc.Graph(id="plot-total"), label="Total cases"), dbc.Tab(dcc.Graph(id="plot-active"), label="Active cases") ]) ]) ])])# Python functions for about [email protected](output=Output("about","is_open"), inputs=[Input("about-popover","n_clicks")], state=[State("about","is_open")])def about_popover(n, is_open): if n: return not is_open return [email protected](output=Output("about-popover","active"), inputs=[Input("about-popover","n_clicks")], state=[State("about-popover","active")])def about_active(n, active): if n: return not active return active# Python function to plot total [email protected](output=Output("plot-total","figure"), inputs=[Input("country","value")]) def plot_total_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_total(model.today)# Python function to plot active [email protected](output=Output("plot-active","figure"), inputs=[Input("country","value")])def plot_active_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_active(model.today)# Python function to render output [email protected](output=Output("output-panel","children"), inputs=[Input("country","value")])def render_output_panel(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) peak_day, num_max, total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days = result.get_panel() peak_color = "white" if model.today > peak_day else "red" panel = html.Div([ html.H4(country), dbc.Card(body=True, className="text-white bg-primary", children=[ html.H6("Total cases until today:", style={"color":"white"}), html.H3("{:,.0f}".format(total_cases_until_today), style={"color":"white"}), html.H6("Total cases in 30 days:", className="text-danger"), html.H3("{:,.0f}".format(total_cases_in_30days), className="text-danger"), html.H6("Active cases today:", style={"color":"white"}), html.H3("{:,.0f}".format(active_cases_today), style={"color":"white"}), html.H6("Active cases in 30 days:", className="text-danger"), html.H3("{:,.0f}".format(active_cases_in_30days), className="text-danger"), html.H6("Peak day:", style={"color":peak_color}), html.H3(peak_day.strftime("%Y-%m-%d"), style={"color":peak_color}), html.H6("with {:,.0f} cases".format(num_max), style={"color":peak_color}) ]) ]) return panel How do we find out if we made any errors in the code? We run the application. Only one line of code is necessary to run the whole thing and I shall put it in the run.py file (on root level): from application.dash import appfrom settings import configapp.run_server(debug=config.debug, host=config.host, port=config.port) Run the following command in the terminal: python run.py and you should see this: Great job, the application is up and running! Do you want to make your application available for anyone? Then you have to deploy it somewhere. I usually use Heroku, a cloud platform as a service that allows deploying a PoC app with just a free account. You can link a Github repo and deploy one of the branches. In order for this to work, the app needs a requirements.txt and a Procfile. In the Setup section, I already put the command to create the text file with the required packages. In regard to the Procfile, it’s just the command line to run the app that I put in the previous section. Heroku will run it and there you go: This article has been a tutorial to show how easy is to build a nice looking web application with Dash and Dash Bootstrap Components that embeds all the CSS and JS of Bootstrap. I used my Covid-19 infection forecaster app as example, going through every step from back-end to front-end and even deployment. Now that you know how it works, you can develop your own forecaster, for example changing the data source (i.e. yahoo finance) and the machine learning model (i.e. lstm neural network) you can build a stock price forecaster. I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects. 👉 Let’s Connect 👈 This article is part of the series Web Development with Python, see also:
[ { "code": null, "e": 353, "s": 172, "text": "In this article I will show how to build a web app that forecasts the spread of covid-19 virus within any infected countries using Python, Dash and Bootstrap, that looks like this:" }, { "code": null, "e": 809, "s": 353, "text": "Let me start with this: coding a Dash app is messy... I don’t mean any harm with this, I like Dash and I think it is the future of web development for Python. Dash is a Python (and R) framework for building web applications. It’s built on top of Flask, Plotly.js and React js. It is open source, its apps run on the web browser. Dash is super convenient if you are better in Python than Javascript because allows you to build dashboards using pure Python." }, { "code": null, "e": 1241, "s": 809, "text": "I don’t know if you’ve ever seen a dash application code. It’s a mess: the code comes out really long as you need to write every html Div with contents and properties, just like an html page before that Bootstrap was invented. Bootstrap is an open source toolkit for developing with HTML, CSS, and JS. It is the most used library for web development thanks to its extensive prebuilt components and powerful plugins built on jQuery." }, { "code": null, "e": 1501, "s": 1241, "text": "I love Boostrap, not only because the output is always pretty good looking, but especially because it saves you lines and lines of HTML, CSS and JS code. What if I tell you that it is possible also for Dash applications? You like the sound of that, don’t you?" }, { "code": null, "e": 1750, "s": 1501, "text": "Through this tutorial I will explain step by step how Bootstrap can be easily integrated in Dash and how to build and deploy a web application, using my Covid-19 infection forecaster app as an example (link below, it might take 30 seconds to load)." }, { "code": null, "e": 1785, "s": 1750, "text": "app-virus-forecaster.herokuapp.com" }, { "code": null, "e": 2023, "s": 1785, "text": "I will present some useful Python code that can be easily used in other similar cases (just copy, paste, run) and walk through every line of code with comments, so that you can easily replicate this example (link to the full code below)." }, { "code": null, "e": 2034, "s": 2023, "text": "github.com" }, { "code": null, "e": 2350, "s": 2034, "text": "I’ll use the most popular dataset in these days of quarantine: CSSE COVID-19 dataset. It presents the time series of the number of confirmed cases of contagion reported by each country every day since the pandemic started. This dataset is freely available on the GitHub of the Johns Hopkins University (link below)." }, { "code": null, "e": 2361, "s": 2350, "text": "github.com" }, { "code": null, "e": 2395, "s": 2361, "text": "In particular, I will go through:" }, { "code": null, "e": 2420, "s": 2395, "text": "Setup of the environment" }, { "code": null, "e": 2480, "s": 2420, "text": "Back-end: Write the model to get, process and plot the data" }, { "code": null, "e": 2529, "s": 2480, "text": "Front-end: Build the app with Dash and Bootstrap" }, { "code": null, "e": 2544, "s": 2529, "text": "Deploy the app" }, { "code": null, "e": 2619, "s": 2544, "text": "First of all, I will install the following libraries through the terminal:" }, { "code": null, "e": 2691, "s": 2619, "text": "pip install dashpip install dash-bootstrap-componentspip install pandas" }, { "code": null, "e": 3258, "s": 2691, "text": "The command to install dash will also download useful packages like dash-core-components, dash-html-components and plotly. Similarly, pandas installation includes numpy and scipy that I will use later as well. I assume you already know those, therefore I shall take a moment to introduce Dash Bootstrap Components: basically it’s what does the trick to integrate Bootstrap in Dash and makes easier to build consistently styled apps with complex and responsive layouts. I’m a fan of this library because it saves a huge number of lines of dash code, you’ll see later." }, { "code": null, "e": 3408, "s": 3258, "text": "After installing all you need, I would recommend running the following command on the terminal to save the requirements on the appropriate text file:" }, { "code": null, "e": 3438, "s": 3408, "text": "pip freeze > requirements.txt" }, { "code": null, "e": 3517, "s": 3438, "text": "In regard to the folder structure, I put 4 fundamental elements on root level:" }, { "code": null, "e": 3593, "s": 3517, "text": "application folder: where all the dash code is going to be, in dash.py file" }, { "code": null, "e": 3645, "s": 3593, "text": "python folder: where I place the logic of the model" }, { "code": null, "e": 3701, "s": 3645, "text": "settings folder: where there are all the configurations" }, { "code": null, "e": 3795, "s": 3701, "text": "run.py file: that runs the whole thing if executed on the terminal with the following command" }, { "code": null, "e": 3809, "s": 3795, "text": "python run.py" }, { "code": null, "e": 4083, "s": 3809, "text": "Those mentioned so far are all I need to make the app work, however, there are some other useful but unnecessary things that I added like static images (in application folder), comments (in settings folder), Procfile and requirements.txt used in deployment (on root level)." }, { "code": null, "e": 4141, "s": 4083, "text": "To summarize, the app shall have the following structure:" }, { "code": null, "e": 4253, "s": 4141, "text": "Now that it’s all set, I will go through each python file and show the code in it. Let’s get started, shall we?" }, { "code": null, "e": 4429, "s": 4253, "text": "Firstly, I will write the class to get Covid-19 infection data, then I will build the model that learns from past observation and forecast the future trend of the time series." }, { "code": null, "e": 5192, "s": 4429, "text": "In data.py (inside the python folder) I’ll define the “Data” class with a method that shall be executed when the app starts, meaning that every time the page of the browser where the app runs is loaded, the back-end gets fresh data directly from the source (“get_data” function in the code below). It’s important to save the list of countries because it will be shown to users on the dashboard for selecting a specific country. The Data class has also the task to receive the input from the front-end, the country selected by the user, filter and process data (“process_data” function in the code below). Before filtering for a specific country, I’d create an aggregated time series called “World” which shall be the default selected country when the app starts." }, { "code": null, "e": 5243, "s": 5192, "text": "In python terms, the data.py file looks like this:" }, { "code": null, "e": 6082, "s": 5243, "text": "import pandas as pdclass Data(): def get_data(self): self.dtf_cases = pd.read_csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\", sep=\",\") self.countrylist = [\"World\"] + self.dtf_cases[\"Country/Region\"].unique().tolist() @staticmethod def group_by_country(dtf, country): dtf = dtf.drop(['Province/State','Lat','Long'], axis=1).groupby(\"Country/Region\").sum().T dtf[\"World\"] = dtf.sum(axis=1) dtf = dtf[country] dtf.index = pd.to_datetime(dtf.index, infer_datetime_format=True) ts = pd.DataFrame(index=dtf.index, data=dtf.values, columns=[\"data\"]) return ts def process_data(self, country): self.dtf = self.group_by_country(self.dtf_cases, country)" }, { "code": null, "e": 6484, "s": 6082, "text": "Now, I’ll build the model to fit data and forecast. The purpose of this article is not to dig in what is the most appropriate model for this dataset, therefore I’ll keep it simple: I am going to use a parametric curve fitting approach, optimizing the parameters of a logistic function for each country time series. If you are interested in this basic modelling approach you can find it explained here." }, { "code": null, "e": 6881, "s": 6484, "text": "In model.py (inside the python folder) I’ll define the “Model” class with a method (“forecast” function in the code below) that shall be executed on the World time series when the app starts and each time that a specific country is selected from the front-end. This class has the job to fit the best logistic function on the selected country data (with scipy) and produce a pandas dataframe with:" }, { "code": null, "e": 6972, "s": 6881, "text": "the actual data and the fitted logistic model, which shall be used to plot the total cases" }, { "code": null, "e": 7109, "s": 6972, "text": "the daily change of the actual data and the fitted logistic model (delta t = y t — y t-1), which shall be used to plot the active cases." }, { "code": null, "e": 7181, "s": 7109, "text": "To give an illustration, the model.py file contains the following code:" }, { "code": null, "e": 9289, "s": 7181, "text": "import pandas as pdimport numpy as npfrom scipy import optimizeclass Model(): def __init__(self, dtf): self.dtf = dtf @staticmethod def f(X, c, k, m): y = c / (1 + np.exp(-k*(X-m))) return y @staticmethod def fit_parametric(X, y, f, p0): model, cov = optimize.curve_fit(f, X, y, maxfev=10000, p0=p0) return model @staticmethod def forecast_parametric(model, f, X): preds = f(X, model[0], model[1], model[2]) return preds @staticmethod def generate_indexdate(start): index = pd.date_range(start=start, periods=30, freq=\"D\") index = index[1:] return index @staticmethod def add_diff(dtf): ## create delta columns dtf[\"delta_data\"] = dtf[\"data\"] - dtf[\"data\"].shift(1) dtf[\"delta_forecast\"] = dtf[\"forecast\"] - dtf[\"forecast\"].shift(1) ## fill Nas dtf[\"delta_data\"] = dtf[\"delta_data\"].fillna(method='bfill') dtf[\"delta_forecast\"] = dtf[\"delta_forecast\"].fillna(method='bfill') ## interpolate outlier idx = dtf[pd.isnull(dtf[\"data\"])][\"delta_forecast\"].index[0] posx = dtf.index.tolist().index(idx) posx_a = posx - 1 posx_b = posx + 1 dtf[\"delta_forecast\"].iloc[posx] = (dtf[\"delta_forecast\"].iloc[posx_a] + dtf[\"delta_forecast\"].iloc[posx_b])/2 return dtf def forecast(self): ## fit y = self.dtf[\"data\"].values t = np.arange(len(y)) model = self.fit_parametric(t, y, self.f, p0=[np.max(y),1,1]) fitted = self.f(t, model[0], model[1], model[2]) self.dtf[\"forecast\"] = fitted ## forecast t_ahead = np.arange(len(y)+1, len(y)+30) forecast = self.forecast_parametric(model, self.f, t_ahead) ## create dtf self.today = self.dtf.index[-1] idxdates = self.generate_indexdate(start=self.today) preds = pd.DataFrame(data=forecast, index=idxdates, columns=[\"forecast\"]) self.dtf = self.dtf.append(preds) ## add diff self.dtf = self.add_diff(self.dtf)" }, { "code": null, "e": 9495, "s": 9289, "text": "It’s time to make some cool plots and the best tool for the job is Plotly as Dash is built on top of it. I will put in result.py (inside the python folder) the class that is going to take care of this with" }, { "code": null, "e": 9602, "s": 9495, "text": "the method to plot the total cases time series and its forecast (“plot_total” function in the code below):" }, { "code": null, "e": 9711, "s": 9602, "text": "the method to plot the active cases time series and its forecast (“plot_active” function in the code below):" }, { "code": null, "e": 9817, "s": 9711, "text": "the method to retrieve some statistics to show on the front-end (“get_panel” function in the code below):" }, { "code": null, "e": 9857, "s": 9817, "text": "Here’s the code full code in result.py:" }, { "code": null, "e": 12855, "s": 9857, "text": "import pandas as pdimport plotly.graph_objects as goclass Result(): def __init__(self, dtf): self.dtf = dtf @staticmethod def calculate_peak(dtf): data_max = dtf[\"delta_data\"].max() forecast_max = dtf[\"delta_forecast\"].max() if data_max >= forecast_max: peak_day = dtf[dtf[\"delta_data\"]==data_max].index[0] return peak_day, data_max else: peak_day = dtf[dtf[\"delta_forecast\"]==forecast_max].index[0] return peak_day, forecast_max @staticmethod def calculate_max(dtf): total_cases_until_today = dtf[\"data\"].max() total_cases_in_30days = dtf[\"forecast\"].max() active_cases_today = dtf[\"delta_data\"].max() active_cases_in_30days = dtf[\"delta_forecast\"].max() return total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days def plot_total(self, today): ## main plots fig = go.Figure() fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf[\"data\"], mode='markers', name='data', line={\"color\":\"black\"})) fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf[\"forecast\"], mode='none', name='forecast', fill='tozeroy')) ## add slider fig.update_xaxes(rangeslider_visible=True) ## set background color fig.update_layout(plot_bgcolor='white', autosize=False, width=1000, height=550) ## add vline fig.add_shape({\"x0\":today, \"x1\":today, \"y0\":0, \"y1\":self.dtf[\"forecast\"].max(), \"type\":\"line\", \"line\":{\"width\":2,\"dash\":\"dot\"} }) fig.add_trace(go.Scatter(x=[today], y=[self.dtf[\"forecast\"].max()], text=[\"today\"], mode=\"text\", line={\"color\":\"green\"}, showlegend=False)) return fig def plot_active(self, today): ## main plots fig = go.Figure() fig.add_trace(go.Bar(x=self.dtf.index, y=self.dtf[\"delta_data\"], name='data', marker_color='black')) fig.add_trace(go.Scatter(x=self.dtf.index, y=self.dtf[\"delta_forecast\"], mode='none', name='forecast', fill='tozeroy')) ## add slider fig.update_xaxes(rangeslider_visible=True) ## set background color fig.update_layout(plot_bgcolor='white', autosize=False, width=1000, height=550) ## add vline fig.add_shape({\"x0\":today, \"x1\":today, \"y0\":0, \"y1\":self.dtf[\"delta_forecast\"].max(), \"type\":\"line\", \"line\":{\"width\":2,\"dash\":\"dot\"} }) fig.add_trace(go.Scatter(x=[today], y=[self.dtf[\"delta_forecast\"].max()], text=[\"today\"], mode=\"text\", line={\"color\":\"green\"}, showlegend=False)) return fig def get_panel(self): peak_day, num_max = self.calculate_peak(self.dtf) total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days = self.calculate_max(self.dtf) return peak_day, num_max, total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days" }, { "code": null, "e": 13076, "s": 12855, "text": "Finally, here we are, about to code the app using Dash and Dash Bootstrap Components (henceforth as “dbc”), I am going to explain it step by step and also provide the full code of dash.py (inside the application folder)." }, { "code": null, "e": 13116, "s": 13076, "text": "For this we need the following imports:" }, { "code": null, "e": 13286, "s": 13116, "text": "import dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbc" }, { "code": null, "e": 13420, "s": 13286, "text": "As start, I need to define the app instance and in doing this dbc already provides a great feature in choosing a Bootstrap CSS theme:" }, { "code": null, "e": 13475, "s": 13420, "text": "app = dash.Dash(external_stylesheets=[dbc.themes.LUX])" }, { "code": null, "e": 13744, "s": 13475, "text": "Following a visual order, I shall now approach the top navbar. I want something cool and reactive on click, with pop-ups and a drop-down menu, but I’d like to not waste too much time on writing CSS and JS code. To put it another way, I want to use Bootstrap like this:" }, { "code": null, "e": 13818, "s": 13744, "text": "Similarly to this html, we can use dbc to crate the navbar and its items:" }, { "code": null, "e": 13888, "s": 13818, "text": "dbc.Nav([ dbc.NavItem(), dbc.NavItem(), dbc.DropdownMenu()])" }, { "code": null, "e": 14053, "s": 13888, "text": "You got the gimmick, right? Dash and Dbc replicate the same structure and logic of the html syntax. With this in mind, inside each item we can add whatever we want:" }, { "code": null, "e": 14414, "s": 14053, "text": "Moving on with the input form, I‘d like to get a simple drop-down menu with all the possible countries as options and the “World” as default selection. In order to do this, it’s necessary to read the data before coding the drop-down menu object. Do you remember the Data class written before in data.py (python folder)? Well, now it’s the right time to use it:" }, { "code": null, "e": 14471, "s": 14414, "text": "from python.data import Datadata = Data()data.get_data()" }, { "code": null, "e": 14607, "s": 14471, "text": "Now that we have the country list in the Data object, we can write the drop-down menu and set the options in it with a simple for loop:" }, { "code": null, "e": 14730, "s": 14607, "text": "dcc.Dropdown(id=\"country\", options=[{\"label\":x,\"value\":x} for x in data.countrylist], value=\"World\")])" }, { "code": null, "e": 15086, "s": 14730, "text": "In Dash, if not specifically programmed, the output will be put in rows, one below the other. However, I’d like to have all contained in the screen size, so users do not need to scroll down. That’s why I am going to use tabs and each one will show one of the 2 plots I coded before in result.py (in python folder) with plotly. With dbc this is super easy:" }, { "code": null, "e": 15240, "s": 15086, "text": "dbc.Tabs([ dbc.Tab(dcc.Graph(id=\"plot-total\"), label=\"Total cases\"), dbc.Tab(dcc.Graph(id=\"plot-active\"), label=\"Active cases\") ])" }, { "code": null, "e": 15660, "s": 15240, "text": "I bet you’re wondering “how does the app know that in the first tab it has to put the first plot and in the second the other?”. Well, you’re not wrong, the app needs a link between the html and the Python code output. In Dash this is done with callbacks. A callback is nothing more than a decorator, a function that takes another function and extends the behavior of the latter function without explicitly modifying it." }, { "code": null, "e": 15910, "s": 15660, "text": "Let’s take the plot of total cases as an example: I need a function that takes the country selected from the front-end as input and returns the plot as output using the Model and Result classes I coded before (in python folder). Something like this:" }, { "code": null, "e": 16126, "s": 15910, "text": "def plot_total_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_total(model.today)" }, { "code": null, "e": 16422, "s": 16126, "text": "As you surely noticed, in the previous code where I defined the tabs, I put an id in the first one (id=”plot-total”). So I need to add, on top of this function, a callback decorator to tell the app that the figure the back-end will plot refers to that id and that the input is the country value." }, { "code": null, "e": 16524, "s": 16422, "text": "@app.callback(output=Output(\"plot-total\",\"figure\"), inputs=[Input(\"country\",\"value\")]) " }, { "code": null, "e": 16819, "s": 16524, "text": "Ultimately, the panel on the right with some statistics is a little different because the python function doesn’t return a plot like before but an entire html div. In fact, the dash code this time is going to be inside the callback function that calculate those numbers. I’m talking about this:" }, { "code": null, "e": 16974, "s": 16819, "text": "This covers pretty much all the elements of the front-end layout, it’s a very basic application with one single input and few outputs (plots and numbers)." }, { "code": null, "e": 16996, "s": 16974, "text": "Full code of dash.py:" }, { "code": null, "e": 21866, "s": 16996, "text": "# Setupimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom settings import config, aboutfrom python.data import Datafrom python.model import Modelfrom python.result import Result# Read datadata = Data()data.get_data()# App Instanceapp = dash.Dash(name=config.name, assets_folder=config.root+\"/application/static\", external_stylesheets=[dbc.themes.LUX, config.fontawesome])app.title = config.name# Navbarnavbar = dbc.Nav(className=\"nav nav-pills\", children=[ ## logo/home dbc.NavItem(html.Img(src=app.get_asset_url(\"logo.PNG\"), height=\"40px\")), ## about dbc.NavItem(html.Div([ dbc.NavLink(\"About\", href=\"/\", id=\"about-popover\", active=False), dbc.Popover(id=\"about\", is_open=False, target=\"about-popover\", children=[ dbc.PopoverHeader(\"How it works\"), dbc.PopoverBody(about.txt) ]) ])), ## links dbc.DropdownMenu(label=\"Links\", nav=True, children=[ dbc.DropdownMenuItem([html.I(className=\"fa fa-linkedin\"), \" Contacts\"], href=config.contacts, target=\"_blank\"), dbc.DropdownMenuItem([html.I(className=\"fa fa-github\"), \" Code\"], href=config.code, target=\"_blank\") ])])# Inputinputs = dbc.FormGroup([ html.H4(\"Select Country\"), dcc.Dropdown(id=\"country\", options=[{\"label\":x,\"value\":x} for x in data.countrylist], value=\"World\")])# App Layoutapp.layout = dbc.Container(fluid=True, children=[ ## Top html.H1(config.name, id=\"nav-pills\"), navbar, html.Br(),html.Br(),html.Br(), ## Body dbc.Row([ ### input + panel dbc.Col(md=3, children=[ inputs, html.Br(),html.Br(),html.Br(), html.Div(id=\"output-panel\") ]), ### plots dbc.Col(md=9, children=[ dbc.Col(html.H4(\"Forecast 30 days from today\"), width={\"size\":6,\"offset\":3}), dbc.Tabs(className=\"nav nav-pills\", children=[ dbc.Tab(dcc.Graph(id=\"plot-total\"), label=\"Total cases\"), dbc.Tab(dcc.Graph(id=\"plot-active\"), label=\"Active cases\") ]) ]) ])])# Python functions for about [email protected](output=Output(\"about\",\"is_open\"), inputs=[Input(\"about-popover\",\"n_clicks\")], state=[State(\"about\",\"is_open\")])def about_popover(n, is_open): if n: return not is_open return [email protected](output=Output(\"about-popover\",\"active\"), inputs=[Input(\"about-popover\",\"n_clicks\")], state=[State(\"about-popover\",\"active\")])def about_active(n, active): if n: return not active return active# Python function to plot total [email protected](output=Output(\"plot-total\",\"figure\"), inputs=[Input(\"country\",\"value\")]) def plot_total_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_total(model.today)# Python function to plot active [email protected](output=Output(\"plot-active\",\"figure\"), inputs=[Input(\"country\",\"value\")])def plot_active_cases(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) return result.plot_active(model.today)# Python function to render output [email protected](output=Output(\"output-panel\",\"children\"), inputs=[Input(\"country\",\"value\")])def render_output_panel(country): data.process_data(country) model = Model(data.dtf) model.forecast() model.add_deaths(data.mortality) result = Result(model.dtf) peak_day, num_max, total_cases_until_today, total_cases_in_30days, active_cases_today, active_cases_in_30days = result.get_panel() peak_color = \"white\" if model.today > peak_day else \"red\" panel = html.Div([ html.H4(country), dbc.Card(body=True, className=\"text-white bg-primary\", children=[ html.H6(\"Total cases until today:\", style={\"color\":\"white\"}), html.H3(\"{:,.0f}\".format(total_cases_until_today), style={\"color\":\"white\"}), html.H6(\"Total cases in 30 days:\", className=\"text-danger\"), html.H3(\"{:,.0f}\".format(total_cases_in_30days), className=\"text-danger\"), html.H6(\"Active cases today:\", style={\"color\":\"white\"}), html.H3(\"{:,.0f}\".format(active_cases_today), style={\"color\":\"white\"}), html.H6(\"Active cases in 30 days:\", className=\"text-danger\"), html.H3(\"{:,.0f}\".format(active_cases_in_30days), className=\"text-danger\"), html.H6(\"Peak day:\", style={\"color\":peak_color}), html.H3(peak_day.strftime(\"%Y-%m-%d\"), style={\"color\":peak_color}), html.H6(\"with {:,.0f} cases\".format(num_max), style={\"color\":peak_color}) ]) ]) return panel" }, { "code": null, "e": 22057, "s": 21866, "text": "How do we find out if we made any errors in the code? We run the application. Only one line of code is necessary to run the whole thing and I shall put it in the run.py file (on root level):" }, { "code": null, "e": 22187, "s": 22057, "text": "from application.dash import appfrom settings import configapp.run_server(debug=config.debug, host=config.host, port=config.port)" }, { "code": null, "e": 22230, "s": 22187, "text": "Run the following command in the terminal:" }, { "code": null, "e": 22244, "s": 22230, "text": "python run.py" }, { "code": null, "e": 22269, "s": 22244, "text": "and you should see this:" }, { "code": null, "e": 22315, "s": 22269, "text": "Great job, the application is up and running!" }, { "code": null, "e": 22522, "s": 22315, "text": "Do you want to make your application available for anyone? Then you have to deploy it somewhere. I usually use Heroku, a cloud platform as a service that allows deploying a PoC app with just a free account." }, { "code": null, "e": 22581, "s": 22522, "text": "You can link a Github repo and deploy one of the branches." }, { "code": null, "e": 22899, "s": 22581, "text": "In order for this to work, the app needs a requirements.txt and a Procfile. In the Setup section, I already put the command to create the text file with the required packages. In regard to the Procfile, it’s just the command line to run the app that I put in the previous section. Heroku will run it and there you go:" }, { "code": null, "e": 23431, "s": 22899, "text": "This article has been a tutorial to show how easy is to build a nice looking web application with Dash and Dash Bootstrap Components that embeds all the CSS and JS of Bootstrap. I used my Covid-19 infection forecaster app as example, going through every step from back-end to front-end and even deployment. Now that you know how it works, you can develop your own forecaster, for example changing the data source (i.e. yahoo finance) and the machine learning model (i.e. lstm neural network) you can build a stock price forecaster." }, { "code": null, "e": 23549, "s": 23431, "text": "I hope you enjoyed it! Feel free to contact me for questions and feedback or just to share your interesting projects." }, { "code": null, "e": 23567, "s": 23549, "text": "👉 Let’s Connect 👈" } ]
Python MongoDB - Insert Document
You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter. Following is the syntax of the insert method. >db.COLLECTION_NAME.insert(DOCUMENT_NAME) > use mydb switched to db mydb > db.createCollection("sample") { "ok" : 1 } > doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} { "name" : "Ram", "age" : "26", "city" : "Hyderabad" } > db.sample.insert(doc1) WriteResult({ "nInserted" : 1 }) > Similarly, you can also insert multiple documents using the insert() method. > use testDB switched to db testDB > db.createCollection("sample") { "ok" : 1 } > data = [ {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }, {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" } ] [ {"_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad"}, {"_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore"}, {"_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai"} ] > db.sample.insert(data) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format. Following example inserts a document in the collection named example. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"} coll.insert_one(doc1) print(coll.find_one()) {'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'} To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method. from pymongo import MongoClient #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] #Creating a collection coll = db['example'] #Inserting document into a collection data = [ {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"}, {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"}, {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"} ] res = coll.insert_many(data) print("Data inserted ......") print(res.inserted_ids) Data inserted ...... ['101', '102', '103'] 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": 2050, "s": 1934, "text": "You can store documents into MongoDB using the insert() method. This method accepts a JSON document as a parameter." }, { "code": null, "e": 2096, "s": 2050, "text": "Following is the syntax of the insert method." }, { "code": null, "e": 2139, "s": 2096, "text": ">db.COLLECTION_NAME.insert(DOCUMENT_NAME)\n" }, { "code": null, "e": 2389, "s": 2139, "text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> doc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\n{ \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\" }\n> db.sample.insert(doc1)\nWriteResult({ \"nInserted\" : 1 })\n>" }, { "code": null, "e": 2466, "s": 2389, "text": "Similarly, you can also insert multiple documents using the insert() method." }, { "code": null, "e": 3214, "s": 2466, "text": "> use testDB\nswitched to db testDB\n> db.createCollection(\"sample\")\n{ \"ok\" : 1 }\n> data = [\n {\"_id\": \"1001\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}, \n {\"_id\": \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\" }, \n {\"_id\": \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\" }\n]\n[\n {\"_id\" : \"1001\", \"name\" : \"Ram\", \"age\" : \"26\", \"city\" : \"Hyderabad\"},\n {\"_id\" : \"1002\", \"name\" : \"Rahim\", \"age\" : 27, \"city\" : \"Bangalore\"},\n {\"_id\" : \"1003\", \"name\" : \"Robert\", \"age\" : 28, \"city\" : \"Mumbai\"}\n]\n> db.sample.insert(data)\nBulkWriteResult({\n \"writeErrors\" : [ ],\n \"writeConcernErrors\" : [ ],\n \"nInserted\" : 3,\n \"nUpserted\" : 0,\n \"nMatched\" : 0,\n \"nModified\" : 0,\n \"nRemoved\" : 0,\n \"upserted\" : [ ]\n})\n>" }, { "code": null, "e": 3359, "s": 3214, "text": "Pymongo provides a method named insert_one() to insert a document in MangoDB. To this method, we need to pass the document in dictionary format." }, { "code": null, "e": 3429, "s": 3359, "text": "Following example inserts a document in the collection named example." }, { "code": null, "e": 3768, "s": 3429, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndoc1 = {\"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"}\ncoll.insert_one(doc1)\nprint(coll.find_one())" }, { "code": null, "e": 3864, "s": 3768, "text": "{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}\n" }, { "code": null, "e": 3966, "s": 3864, "text": "To insert multiple documents into MongoDB using pymongo, you need to invoke the insert_many() method." }, { "code": null, "e": 4502, "s": 3966, "text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncoll = db['example']\n\n#Inserting document into a collection\ndata = [\n {\"_id\": \"101\", \"name\": \"Ram\", \"age\": \"26\", \"city\": \"Hyderabad\"},\n {\"_id\": \"102\", \"name\": \"Rahim\", \"age\": \"27\", \"city\": \"Bangalore\"},\n {\"_id\": \"103\", \"name\": \"Robert\", \"age\": \"28\", \"city\": \"Mumbai\"}\n]\nres = coll.insert_many(data)\nprint(\"Data inserted ......\")\nprint(res.inserted_ids)" }, { "code": null, "e": 4546, "s": 4502, "text": "Data inserted ......\n['101', '102', '103']\n" }, { "code": null, "e": 4583, "s": 4546, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4599, "s": 4583, "text": " Malhar Lathkar" }, { "code": null, "e": 4632, "s": 4599, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4651, "s": 4632, "text": " Arnab Chakraborty" }, { "code": null, "e": 4686, "s": 4651, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4708, "s": 4686, "text": " In28Minutes Official" }, { "code": null, "e": 4742, "s": 4708, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4770, "s": 4742, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4805, "s": 4770, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4819, "s": 4805, "text": " Lets Kode It" }, { "code": null, "e": 4852, "s": 4819, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4869, "s": 4852, "text": " Abhilash Nelson" }, { "code": null, "e": 4876, "s": 4869, "text": " Print" }, { "code": null, "e": 4887, "s": 4876, "text": " Add Notes" } ]
Python Pandas – Find unique values from multiple columns
To find unique values from multiple columns, use the unique() method. Let’s say you have Employee Records with “EmpName” and “Zone” in your Pandas DataFrame. The name and zone can get repeated since two employees can have similar names and a zone can have more than one employee. In that case, if you want unique Employee names, then use the unique() for DataFrame. At first, import the required library. Here, we have set pd as an alias − import pandas as pd At first, create a DataFrame. Here, we have two columns − dataFrame = pd.DataFrame( { "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],"Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North'] } ) Fetch unique Employee Names and Zone from the DataFrame column “EmpName” and “Zone” − {pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()} Following is the complete code − import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],"Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North'] } ) print("DataFrame ...\n",dataFrame) # Fetch unique values from multiple columns print(f"\nFetching unique Values from the two columns and concatenate them:\n \ {pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()}") This will produce the following output − DataFrame ... EmpName Zone 0 John North 1 Ted South 2 Jacob South 3 Scarlett East 4 Ami West 5 Ted East 6 Scarlett North Fetching unique Values from the two columns and concatenate them: ['John' 'Ted' 'Jacob' 'Scarlett' 'Ami' 'North' 'South' 'East' 'West']
[ { "code": null, "e": 1428, "s": 1062, "text": "To find unique values from multiple columns, use the unique() method. Let’s say you have Employee Records with “EmpName” and “Zone” in your Pandas DataFrame. The name and zone can get repeated since two employees can have similar names and a zone can have more than one employee. In that case, if you want unique Employee names, then use the unique() for DataFrame." }, { "code": null, "e": 1502, "s": 1428, "text": "At first, import the required library. Here, we have set pd as an alias −" }, { "code": null, "e": 1522, "s": 1502, "text": "import pandas as pd" }, { "code": null, "e": 1580, "s": 1522, "text": "At first, create a DataFrame. Here, we have two columns −" }, { "code": null, "e": 1767, "s": 1580, "text": "dataFrame = pd.DataFrame(\n {\n \"EmpName\": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],\"Zone\": ['North', 'South', 'South', 'East', 'West', 'East', 'North']\n }\n)" }, { "code": null, "e": 1853, "s": 1767, "text": "Fetch unique Employee Names and Zone from the DataFrame column “EmpName” and “Zone” −" }, { "code": null, "e": 1916, "s": 1853, "text": "{pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()}" }, { "code": null, "e": 1949, "s": 1916, "text": "Following is the complete code −" }, { "code": null, "e": 2402, "s": 1949, "text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"EmpName\": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],\"Zone\": ['North', 'South', 'South', 'East', 'West', 'East', 'North']\n }\n)\n\nprint(\"DataFrame ...\\n\",dataFrame)\n\n# Fetch unique values from multiple columns\nprint(f\"\\nFetching unique Values from the two columns and concatenate them:\\n \\\n{pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()}\")" }, { "code": null, "e": 2443, "s": 2402, "text": "This will produce the following output −" }, { "code": null, "e": 2746, "s": 2443, "text": "DataFrame ...\n EmpName Zone\n0 John North\n1 Ted South\n2 Jacob South\n3 Scarlett East\n4 Ami West\n5 Ted East\n6 Scarlett North\n\nFetching unique Values from the two columns and concatenate them:\n['John' 'Ted' 'Jacob' 'Scarlett' 'Ami' 'North' 'South' 'East' 'West']" } ]
C library function - strtok()
The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim. Following is the declaration for strtok() function. char *strtok(char *str, const char *delim) str − The contents of this string are modified and broken into smaller strings (tokens). str − The contents of this string are modified and broken into smaller strings (tokens). delim − This is the C string containing the delimiters. These may vary from one call to another. delim − This is the C string containing the delimiters. These may vary from one call to another. This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve. The following example shows the usage of strtok() function. #include <string.h> #include <stdio.h> int main () { char str[80] = "This is - www.tutorialspoint.com - website"; const char s[2] = "-"; char *token; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); } return(0); } Let us compile and run the above program that will produce the following result − This is www.tutorialspoint.com website 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2142, "s": 2007, "text": "The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim." }, { "code": null, "e": 2194, "s": 2142, "text": "Following is the declaration for strtok() function." }, { "code": null, "e": 2237, "s": 2194, "text": "char *strtok(char *str, const char *delim)" }, { "code": null, "e": 2326, "s": 2237, "text": "str − The contents of this string are modified and broken into smaller strings (tokens)." }, { "code": null, "e": 2415, "s": 2326, "text": "str − The contents of this string are modified and broken into smaller strings (tokens)." }, { "code": null, "e": 2512, "s": 2415, "text": "delim − This is the C string containing the delimiters. These may vary from one call to another." }, { "code": null, "e": 2609, "s": 2512, "text": "delim − This is the C string containing the delimiters. These may vary from one call to another." }, { "code": null, "e": 2749, "s": 2609, "text": "This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve." }, { "code": null, "e": 2809, "s": 2749, "text": "The following example shows the usage of strtok() function." }, { "code": null, "e": 3189, "s": 2809, "text": "#include <string.h>\n#include <stdio.h>\n\nint main () {\n char str[80] = \"This is - www.tutorialspoint.com - website\";\n const char s[2] = \"-\";\n char *token;\n \n /* get the first token */\n token = strtok(str, s);\n \n /* walk through other tokens */\n while( token != NULL ) {\n printf( \" %s\\n\", token );\n \n token = strtok(NULL, s);\n }\n \n return(0);\n}" }, { "code": null, "e": 3271, "s": 3189, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3317, "s": 3271, "text": "This is \n www.tutorialspoint.com \n website\n" }, { "code": null, "e": 3350, "s": 3317, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3365, "s": 3350, "text": " Nishant Malik" }, { "code": null, "e": 3400, "s": 3365, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3415, "s": 3400, "text": " Nishant Malik" }, { "code": null, "e": 3450, "s": 3415, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3464, "s": 3450, "text": " Asif Hussain" }, { "code": null, "e": 3497, "s": 3464, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3515, "s": 3497, "text": " Richa Maheshwari" }, { "code": null, "e": 3550, "s": 3515, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3569, "s": 3550, "text": " Vandana Annavaram" }, { "code": null, "e": 3602, "s": 3569, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3614, "s": 3602, "text": " Amit Diwan" }, { "code": null, "e": 3621, "s": 3614, "text": " Print" }, { "code": null, "e": 3632, "s": 3621, "text": " Add Notes" } ]
C program to write an image in PGM format - GeeksforGeeks
24 May, 2018 PGM stands for Portable Gray Map. Saving a 2D array in C as images in PNG, JPG or other formats would need a lot of effort to encode the data in the specified format before writing to a file.However, Netpbm format offers a simple solution with easy portability. A Netpbm format is any graphics format used and defined by the Netpbm project. The portable pixmap format (PPM), the portable graymap format (PGM) and the portable bitmap format (PBM) are image file formats designed to be easily exchanged between platforms. Netpbm is an open-source package of graphics programs and a programming library. It is used mainly in the Unix world, where one can find it included in all major open-source operating system distributions, but also works on macOS, and others. It also works under Microsoft Windows. Each file starts with a two-byte magic number (in ASCII) that identifies the type of file it is (PBM, PGM, and PPM) and its encoding (ASCII or binary). The magic number is a capital P followed by a single-digit number. The ASCII formats allow for human readability and easy transfer to other platforms; the binary formats are more efficient in file size but may have native byte-order issues. In the binary formats, PBM uses 1 bit per pixel, PGM uses 8 bits per pixel, and PPM uses 24 bits per pixel: 8 for red, 8 for green, 8 for blue. The PGM and PPM formats (both ASCII and binary versions) have an additional parameter for the maximum value (numbers of grey between black and white) after the X and Y dimensions and before the actual pixel data. Black is 0 and max value is white. There is a newline character at the end of each line. How to write PGM files?The File format is as follows:1. Magic Number “P2”2. Whitespace (blanks, TABs, CRs, LFs).3. A width, formatted as ASCII characters in decimal.4. Whitespace.5. A height, again in ASCII decimal.6. Whitespace.7. The maximum gray value, again in ASCII decimal.8. Whitespace.9. width X height gray values, each in ASCII decimal, between 0 and the specified maximum value, separated by whitespace, in raster format, from top to bottom. // C program to read a BMP Image and // write the same into a PGM Image file#include <stdio.h> void main(){ int i, j, temp = 0; int width = 13, height = 13; // Suppose the 2D Array to be converted to Image is as given below int image[13][13] = { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31}, { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47}, { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}, { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79}, { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 }, { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111}, { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127}, { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143}, { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159}, { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175}, { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191}, { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207} }; FILE* pgmimg; pgmimg = fopen("pgmimg.pgm", "wb"); // Writing Magic Number to the File fprintf(pgmimg, "P2\n"); // Writing Width and Height fprintf(pgmimg, "%d %d\n", width, height); // Writing the maximum gray value fprintf(pgmimg, "255\n"); int count = 0; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { temp = image[i][j]; // Writing the gray values in the 2D array to the file fprintf(pgmimg, "%d ", temp); } fprintf(pgmimg, "\n"); } fclose(pgmimg);} Steps to compile and execute the code in UbuntuFirst, save the file as “write_pgm_img.c“.For compiling the C file, open terminal (Ctrl+Alt+T) and enter the following line of codegcc -o write_pgm_img write_pgm_img.cFor executing the code enter./write_pgm_imgThe PGM image will be saved as pgmimg.pgm. First, save the file as “write_pgm_img.c“. For compiling the C file, open terminal (Ctrl+Alt+T) and enter the following line of codegcc -o write_pgm_img write_pgm_img.c For executing the code enter./write_pgm_img The PGM image will be saved as pgmimg.pgm. The Image will look like this: Reference: https://en.wikipedia.org/wiki/Netpbm_format Image-Processing C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24486, "s": 24458, "text": "\n24 May, 2018" }, { "code": null, "e": 24748, "s": 24486, "text": "PGM stands for Portable Gray Map. Saving a 2D array in C as images in PNG, JPG or other formats would need a lot of effort to encode the data in the specified format before writing to a file.However, Netpbm format offers a simple solution with easy portability." }, { "code": null, "e": 25006, "s": 24748, "text": "A Netpbm format is any graphics format used and defined by the Netpbm project. The portable pixmap format (PPM), the portable graymap format (PGM) and the portable bitmap format (PBM) are image file formats designed to be easily exchanged between platforms." }, { "code": null, "e": 25288, "s": 25006, "text": "Netpbm is an open-source package of graphics programs and a programming library. It is used mainly in the Unix world, where one can find it included in all major open-source operating system distributions, but also works on macOS, and others. It also works under Microsoft Windows." }, { "code": null, "e": 25507, "s": 25288, "text": "Each file starts with a two-byte magic number (in ASCII) that identifies the type of file it is (PBM, PGM, and PPM) and its encoding (ASCII or binary). The magic number is a capital P followed by a single-digit number." }, { "code": null, "e": 25681, "s": 25507, "text": "The ASCII formats allow for human readability and easy transfer to other platforms; the binary formats are more efficient in file size but may have native byte-order issues." }, { "code": null, "e": 25825, "s": 25681, "text": "In the binary formats, PBM uses 1 bit per pixel, PGM uses 8 bits per pixel, and PPM uses 24 bits per pixel: 8 for red, 8 for green, 8 for blue." }, { "code": null, "e": 26127, "s": 25825, "text": "The PGM and PPM formats (both ASCII and binary versions) have an additional parameter for the maximum value (numbers of grey between black and white) after the X and Y dimensions and before the actual pixel data. Black is 0 and max value is white. There is a newline character at the end of each line." }, { "code": null, "e": 26580, "s": 26127, "text": "How to write PGM files?The File format is as follows:1. Magic Number “P2”2. Whitespace (blanks, TABs, CRs, LFs).3. A width, formatted as ASCII characters in decimal.4. Whitespace.5. A height, again in ASCII decimal.6. Whitespace.7. The maximum gray value, again in ASCII decimal.8. Whitespace.9. width X height gray values, each in ASCII decimal, between 0 and the specified maximum value, separated by whitespace, in raster format, from top to bottom." }, { "code": "// C program to read a BMP Image and // write the same into a PGM Image file#include <stdio.h> void main(){ int i, j, temp = 0; int width = 13, height = 13; // Suppose the 2D Array to be converted to Image is as given below int image[13][13] = { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31}, { 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47}, { 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}, { 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79}, { 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95 }, { 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111}, { 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127}, { 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143}, { 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159}, { 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175, 175}, { 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191}, { 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207} }; FILE* pgmimg; pgmimg = fopen(\"pgmimg.pgm\", \"wb\"); // Writing Magic Number to the File fprintf(pgmimg, \"P2\\n\"); // Writing Width and Height fprintf(pgmimg, \"%d %d\\n\", width, height); // Writing the maximum gray value fprintf(pgmimg, \"255\\n\"); int count = 0; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { temp = image[i][j]; // Writing the gray values in the 2D array to the file fprintf(pgmimg, \"%d \", temp); } fprintf(pgmimg, \"\\n\"); } fclose(pgmimg);}", "e": 28289, "s": 26580, "text": null }, { "code": null, "e": 28589, "s": 28289, "text": "Steps to compile and execute the code in UbuntuFirst, save the file as “write_pgm_img.c“.For compiling the C file, open terminal (Ctrl+Alt+T) and enter the following line of codegcc -o write_pgm_img write_pgm_img.cFor executing the code enter./write_pgm_imgThe PGM image will be saved as pgmimg.pgm." }, { "code": null, "e": 28632, "s": 28589, "text": "First, save the file as “write_pgm_img.c“." }, { "code": null, "e": 28758, "s": 28632, "text": "For compiling the C file, open terminal (Ctrl+Alt+T) and enter the following line of codegcc -o write_pgm_img write_pgm_img.c" }, { "code": null, "e": 28802, "s": 28758, "text": "For executing the code enter./write_pgm_img" }, { "code": null, "e": 28845, "s": 28802, "text": "The PGM image will be saved as pgmimg.pgm." }, { "code": null, "e": 28876, "s": 28845, "text": "The Image will look like this:" }, { "code": null, "e": 28931, "s": 28876, "text": "Reference: https://en.wikipedia.org/wiki/Netpbm_format" }, { "code": null, "e": 28948, "s": 28931, "text": "Image-Processing" }, { "code": null, "e": 28959, "s": 28948, "text": "C Language" }, { "code": null, "e": 28970, "s": 28959, "text": "C Programs" }, { "code": null, "e": 29068, "s": 28970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29096, "s": 29068, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 29142, "s": 29096, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29154, "s": 29142, "text": "fork() in C" }, { "code": null, "e": 29186, "s": 29154, "text": "Command line arguments in C/C++" }, { "code": null, "e": 29208, "s": 29186, "text": "Function Pointer in C" }, { "code": null, "e": 29221, "s": 29208, "text": "Strings in C" }, { "code": null, "e": 29262, "s": 29221, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29300, "s": 29262, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 29341, "s": 29300, "text": "C Program to read contents of Whole File" } ]
Design Front Middle Back Queue using STL - GeeksforGeeks
04 Aug, 2021 Design a data structure that supports the following operations in queue efficiently: push__front(x): Insert an element at the front of the queue. push__middle(x): Inserts element at the middle of the queue. push__back(x): Inserts element at the back of the queue. pop__front() Removes the front element of the queue and returns it. If the queue is empty, returns -1. pop__middle(): Removes the middle element of the queue and returns it. If the queue is empty, returns -1. pop__back():Removes the back element of the queue and returns it. If the queue is empty, returns -1. Examples: Deque-based Approach: The problem can be solved using two deque. The idea is to use two deques. Operation at the back of the queue is to be done at the end of the second deque, and operation at the middle is to be done at the end of the first deque. Follow the steps below to solve the problem: If the size of the first deque is greater than the size of the second deque, then remove the end element of the first deque and add it to the front of the second deque. If the size of the second deque exceeds the size of the first deque by 1, then remove the front element of the second deque and push it at the end of the first deque. If the size of the first deque is greater than the second deque, then remove the back element from the first deque and insert it into the second deque. push__front(x): Insert an element x at the front of the first deque using push_front(). push__back(x): Insert an element x at the end of the second deque using push_back() push__middle(x): Insert the element x at the end of the first deque using push_back(). pop__front(): Remove the front element of the first deque if the size of deque is greater than 0 using pop_front(). pop__back(): Remove the end element of the second deque if the size of deque greater than 0 using pop_back(). pop__middle(): Remove the end element of the first deque if the size of deque greater than using pop_back(). Below is the implementation of the above approach: C++ // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Create class Queue.class Queue { // Initialize two deques deque<int> first, second; // Function to balance the size of // first ans second deque void equalizeSizedeque1deque2() { // If size of less than second if (first.size() <= second.size()) return; // Insert the last element of // first deque into second deque second.push_front(first.back()); // Pop the front element // of the deque first.pop_back(); } // Function to balance the size of // second and first deque void equalizeSizedeque2deque1() { // if size of second deque deceed // the first deque by 1 if (second.size() <= first.size() + 1) return; // Insert front element of second // deque into the first first.push_back(second.front()); // Remove front element of // second deque second.pop_front(); } public: // Function to insert element // at front of queue void push__front(int val) { // Insert val into first deque first.push_front(val); // Balancing the size of second equalizeSizedeque1deque2(); } // Function to insert val // into the middle of queue void push__middle(int val) { // Insert val into first deque first.push_back(val); // Balancing the size of // second deque equalizeSizedeque1deque2(); } // Function to insert val // into back of queue void push__back(int val) { // Insert val into second deque second.push_back(val); // Balancing the size of // second deque equalizeSizedeque2deque1(); } // Function to pop front // element from queue int pop__front() { // If first deque and second // deque is empty if (first.empty() && second.empty()) return -1; int ans; // If the first deque // is empty if (first.empty()) { // Stores front element // of second deque ans = second.front(); // Pop front element of // second deque second.pop_front(); } else { // Stores front element // of first deque ans = first.front(); // Pop front element of // first deque first.pop_front(); // Balancing the size of first equalizeSizedeque2deque1(); } return ans; } // Function to pop middle // element of queue int pop__middle() { // If both deques are empty if (first.empty() && second.empty()) return -1; // Stores mid element // of queue int ans; // If size of both deque is equal if (first.size() == second.size()) { // Stores back element // of first deque ans = first.back(); // Pop back element of // first deque first.pop_back(); } else { // Stores front element // of second deque ans = second.front(); // Pop front element // from second deque second.pop_front(); } return ans; } // Function to remove mid // element from queue int pop__back() { // If both the deque are empty if (first.empty() && second.empty()) return -1; // Stores back element from // second deque int ans = second.back(); // Pop back element from // second deque second.pop_back(); // Balancing the size of second equalizeSizedeque1deque2(); return ans; }}; // Driver codeint main(){ Queue q; q.push__front(1); q.push__back(2); q.push__middle(3); cout << q.pop__middle() << " "; cout << q.pop__back() << " "; cout << q.pop__front() << " "; return 0;} 3 2 1 Time Complexity Analysis: List-based Approach: Follow the steps below to solve the problem: push__front(x): Insert an element x at the front of the list using push_front(). push__back(x): Insert an element x at the end of the second list using push_back() push__middle(x): Traverse the list using advance() and then insert the element at mid position of the list using insert() pop__front(): Remove the front element of the list if the size of list greater than 0 using pop_front(), otherwise return -1. pop__back(): Remove the last element of the list if the size of list greater than 0 using pop_back(), otherwise return -1. pop__middle(): If the size of the list greater than 0, then iterate to the middle element of the list using advance() and then erase the element at that position using erase(). Otherwise, return -1. Below is the implementation of the above approach: C++ // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Create structure of queueclass Queue { list<int> l; public: // Function to push element // at front of the queue void push__front(int val) { l.push_front(val); } // Function to push element // at middle of the queue void push__middle(int val) { auto itr = l.begin(); // Traverse the list advance(itr, l.size() / 2); // Insert element into // middle of the list l.insert(itr, val); } // Function to insert element // at the back of the queue void push__back(int val) { l.push_back(val); } // Function to pop element from // front of the queue int pop__front() { // Stores front element // of queue int val = -1; if (l.size()) { val = l.front(); l.pop_front(); } return val; } // Function to pop middle element // of the queue int pop__middle() { int val = -1; if (l.size()) { auto itr = l.begin(); // Traverse the list advance(itr, (l.size() - 1) / 2); val = *itr; // Remove mid element // from queue l.erase(itr); } return val; } // Function to pop end // element of the queue int pop__back() { // Stores back element // of the queue int val = -1; if (l.size()) { val = l.back(); l.pop_back(); } return val; }}; // Drivers codeint main(){ Queue q; q.push__front(1); q.push__back(2); q.push__middle(3); cout << q.pop__middle() << " "; cout << q.pop__back() << " "; cout << q.pop__front() << " "; return 0;} 3 2 1 Time Complexity Analysis: Doubly linked list-based Approach: The problem can also be solved using a doubly-linked list without using STL by storing the address of the head and last node. Follow the steps below to solve the problem: push__front(x):Allocate space for storing the data value x and store the address in the current node pointerInsert the element x by linking the current node between head node and head->next nodeIncrement the capacity by one Allocate space for storing the data value x and store the address in the current node pointer Insert the element x by linking the current node between head node and head->next node Increment the capacity by one push__back(x): Allocate space for storing the data value x and store the address in the current node pointerInsert the element x by linking the current node between the last node and last->previous nodeIncrement the capacity by one Allocate space for storing the data value x and store the address in the current node pointer Insert the element x by linking the current node between the last node and last->previous node Increment the capacity by one push__middle(x): Allocate space for storing the data value x and store the address in the current node pointerInitialize a temp pointer of type nodeReach the middle element of the doubly linked list by doing temp=temp->next half of current capacity timesNow Insert the element x between temp and temp->next by relinking nodesIncrement the capacity by one Allocate space for storing the data value x and store the address in the current node pointer Initialize a temp pointer of type node Reach the middle element of the doubly linked list by doing temp=temp->next half of current capacity times Now Insert the element x between temp and temp->next by relinking nodes Increment the capacity by one pop__front() If the capacity of size is less than 1 then return -1Otherwise, delete the first node between the head and head->next nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element If the capacity of size is less than 1 then return -1 Otherwise, delete the first node between the head and head->next nodes by relinking nodes Decrement the capacity by one Return value of the deleted element pop__back(): If the capacity is less than 1 then return -1Otherwise, delete the end node between the last and last->previous nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element If the capacity is less than 1 then return -1 Otherwise, delete the end node between the last and last->previous nodes by relinking nodes Decrement the capacity by one Return value of the deleted element pop__middle(): Initialize a temp pointer of type nodeReach the middle element of the doubly linked list by doing temp=temp->next half of current capacity timesNow delete temp node between temp->previous and temp->next nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element Initialize a temp pointer of type node Reach the middle element of the doubly linked list by doing temp=temp->next half of current capacity times Now delete temp node between temp->previous and temp->next nodes by relinking nodes Decrement the capacity by one Return value of the deleted element surindertarika1234 gabaa406 cpp-queue STL Linked List Queue Linked List Queue STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Swap nodes in a linked list without swapping data Delete a node in a Doubly Linked List Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Circular Linked List | Set 2 (Traversal) Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 24958, "s": 24930, "text": "\n04 Aug, 2021" }, { "code": null, "e": 25043, "s": 24958, "text": "Design a data structure that supports the following operations in queue efficiently:" }, { "code": null, "e": 25104, "s": 25043, "text": "push__front(x): Insert an element at the front of the queue." }, { "code": null, "e": 25165, "s": 25104, "text": "push__middle(x): Inserts element at the middle of the queue." }, { "code": null, "e": 25222, "s": 25165, "text": "push__back(x): Inserts element at the back of the queue." }, { "code": null, "e": 25325, "s": 25222, "text": "pop__front() Removes the front element of the queue and returns it. If the queue is empty, returns -1." }, { "code": null, "e": 25431, "s": 25325, "text": "pop__middle(): Removes the middle element of the queue and returns it. If the queue is empty, returns -1." }, { "code": null, "e": 25532, "s": 25431, "text": "pop__back():Removes the back element of the queue and returns it. If the queue is empty, returns -1." }, { "code": null, "e": 25542, "s": 25532, "text": "Examples:" }, { "code": null, "e": 25837, "s": 25542, "text": "Deque-based Approach: The problem can be solved using two deque. The idea is to use two deques. Operation at the back of the queue is to be done at the end of the second deque, and operation at the middle is to be done at the end of the first deque. Follow the steps below to solve the problem:" }, { "code": null, "e": 26006, "s": 25837, "text": "If the size of the first deque is greater than the size of the second deque, then remove the end element of the first deque and add it to the front of the second deque." }, { "code": null, "e": 26173, "s": 26006, "text": "If the size of the second deque exceeds the size of the first deque by 1, then remove the front element of the second deque and push it at the end of the first deque." }, { "code": null, "e": 26325, "s": 26173, "text": "If the size of the first deque is greater than the second deque, then remove the back element from the first deque and insert it into the second deque." }, { "code": null, "e": 26413, "s": 26325, "text": "push__front(x): Insert an element x at the front of the first deque using push_front()." }, { "code": null, "e": 26497, "s": 26413, "text": "push__back(x): Insert an element x at the end of the second deque using push_back()" }, { "code": null, "e": 26584, "s": 26497, "text": "push__middle(x): Insert the element x at the end of the first deque using push_back()." }, { "code": null, "e": 26700, "s": 26584, "text": "pop__front(): Remove the front element of the first deque if the size of deque is greater than 0 using pop_front()." }, { "code": null, "e": 26810, "s": 26700, "text": "pop__back(): Remove the end element of the second deque if the size of deque greater than 0 using pop_back()." }, { "code": null, "e": 26919, "s": 26810, "text": "pop__middle(): Remove the end element of the first deque if the size of deque greater than using pop_back()." }, { "code": null, "e": 26970, "s": 26919, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26974, "s": 26970, "text": "C++" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Create class Queue.class Queue { // Initialize two deques deque<int> first, second; // Function to balance the size of // first ans second deque void equalizeSizedeque1deque2() { // If size of less than second if (first.size() <= second.size()) return; // Insert the last element of // first deque into second deque second.push_front(first.back()); // Pop the front element // of the deque first.pop_back(); } // Function to balance the size of // second and first deque void equalizeSizedeque2deque1() { // if size of second deque deceed // the first deque by 1 if (second.size() <= first.size() + 1) return; // Insert front element of second // deque into the first first.push_back(second.front()); // Remove front element of // second deque second.pop_front(); } public: // Function to insert element // at front of queue void push__front(int val) { // Insert val into first deque first.push_front(val); // Balancing the size of second equalizeSizedeque1deque2(); } // Function to insert val // into the middle of queue void push__middle(int val) { // Insert val into first deque first.push_back(val); // Balancing the size of // second deque equalizeSizedeque1deque2(); } // Function to insert val // into back of queue void push__back(int val) { // Insert val into second deque second.push_back(val); // Balancing the size of // second deque equalizeSizedeque2deque1(); } // Function to pop front // element from queue int pop__front() { // If first deque and second // deque is empty if (first.empty() && second.empty()) return -1; int ans; // If the first deque // is empty if (first.empty()) { // Stores front element // of second deque ans = second.front(); // Pop front element of // second deque second.pop_front(); } else { // Stores front element // of first deque ans = first.front(); // Pop front element of // first deque first.pop_front(); // Balancing the size of first equalizeSizedeque2deque1(); } return ans; } // Function to pop middle // element of queue int pop__middle() { // If both deques are empty if (first.empty() && second.empty()) return -1; // Stores mid element // of queue int ans; // If size of both deque is equal if (first.size() == second.size()) { // Stores back element // of first deque ans = first.back(); // Pop back element of // first deque first.pop_back(); } else { // Stores front element // of second deque ans = second.front(); // Pop front element // from second deque second.pop_front(); } return ans; } // Function to remove mid // element from queue int pop__back() { // If both the deque are empty if (first.empty() && second.empty()) return -1; // Stores back element from // second deque int ans = second.back(); // Pop back element from // second deque second.pop_back(); // Balancing the size of second equalizeSizedeque1deque2(); return ans; }}; // Driver codeint main(){ Queue q; q.push__front(1); q.push__back(2); q.push__middle(3); cout << q.pop__middle() << \" \"; cout << q.pop__back() << \" \"; cout << q.pop__front() << \" \"; return 0;}", "e": 31049, "s": 26974, "text": null }, { "code": null, "e": 31055, "s": 31049, "text": "3 2 1" }, { "code": null, "e": 31083, "s": 31057, "text": "Time Complexity Analysis:" }, { "code": null, "e": 31149, "s": 31083, "text": "List-based Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 31230, "s": 31149, "text": "push__front(x): Insert an element x at the front of the list using push_front()." }, { "code": null, "e": 31313, "s": 31230, "text": "push__back(x): Insert an element x at the end of the second list using push_back()" }, { "code": null, "e": 31435, "s": 31313, "text": "push__middle(x): Traverse the list using advance() and then insert the element at mid position of the list using insert()" }, { "code": null, "e": 31561, "s": 31435, "text": "pop__front(): Remove the front element of the list if the size of list greater than 0 using pop_front(), otherwise return -1." }, { "code": null, "e": 31684, "s": 31561, "text": "pop__back(): Remove the last element of the list if the size of list greater than 0 using pop_back(), otherwise return -1." }, { "code": null, "e": 31883, "s": 31684, "text": "pop__middle(): If the size of the list greater than 0, then iterate to the middle element of the list using advance() and then erase the element at that position using erase(). Otherwise, return -1." }, { "code": null, "e": 31934, "s": 31883, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 31938, "s": 31934, "text": "C++" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Create structure of queueclass Queue { list<int> l; public: // Function to push element // at front of the queue void push__front(int val) { l.push_front(val); } // Function to push element // at middle of the queue void push__middle(int val) { auto itr = l.begin(); // Traverse the list advance(itr, l.size() / 2); // Insert element into // middle of the list l.insert(itr, val); } // Function to insert element // at the back of the queue void push__back(int val) { l.push_back(val); } // Function to pop element from // front of the queue int pop__front() { // Stores front element // of queue int val = -1; if (l.size()) { val = l.front(); l.pop_front(); } return val; } // Function to pop middle element // of the queue int pop__middle() { int val = -1; if (l.size()) { auto itr = l.begin(); // Traverse the list advance(itr, (l.size() - 1) / 2); val = *itr; // Remove mid element // from queue l.erase(itr); } return val; } // Function to pop end // element of the queue int pop__back() { // Stores back element // of the queue int val = -1; if (l.size()) { val = l.back(); l.pop_back(); } return val; }}; // Drivers codeint main(){ Queue q; q.push__front(1); q.push__back(2); q.push__middle(3); cout << q.pop__middle() << \" \"; cout << q.pop__back() << \" \"; cout << q.pop__front() << \" \"; return 0;}", "e": 33761, "s": 31938, "text": null }, { "code": null, "e": 33768, "s": 33761, "text": "3 2 1 " }, { "code": null, "e": 33796, "s": 33770, "text": "Time Complexity Analysis:" }, { "code": null, "e": 34002, "s": 33796, "text": "Doubly linked list-based Approach: The problem can also be solved using a doubly-linked list without using STL by storing the address of the head and last node. Follow the steps below to solve the problem:" }, { "code": null, "e": 34226, "s": 34002, "text": "push__front(x):Allocate space for storing the data value x and store the address in the current node pointerInsert the element x by linking the current node between head node and head->next nodeIncrement the capacity by one" }, { "code": null, "e": 34320, "s": 34226, "text": "Allocate space for storing the data value x and store the address in the current node pointer" }, { "code": null, "e": 34407, "s": 34320, "text": "Insert the element x by linking the current node between head node and head->next node" }, { "code": null, "e": 34437, "s": 34407, "text": "Increment the capacity by one" }, { "code": null, "e": 34669, "s": 34437, "text": "push__back(x): Allocate space for storing the data value x and store the address in the current node pointerInsert the element x by linking the current node between the last node and last->previous nodeIncrement the capacity by one" }, { "code": null, "e": 34763, "s": 34669, "text": "Allocate space for storing the data value x and store the address in the current node pointer" }, { "code": null, "e": 34858, "s": 34763, "text": "Insert the element x by linking the current node between the last node and last->previous node" }, { "code": null, "e": 34888, "s": 34858, "text": "Increment the capacity by one" }, { "code": null, "e": 35243, "s": 34888, "text": "push__middle(x): Allocate space for storing the data value x and store the address in the current node pointerInitialize a temp pointer of type nodeReach the middle element of the doubly linked list by doing temp=temp->next half of current capacity timesNow Insert the element x between temp and temp->next by relinking nodesIncrement the capacity by one" }, { "code": null, "e": 35337, "s": 35243, "text": "Allocate space for storing the data value x and store the address in the current node pointer" }, { "code": null, "e": 35376, "s": 35337, "text": "Initialize a temp pointer of type node" }, { "code": null, "e": 35483, "s": 35376, "text": "Reach the middle element of the doubly linked list by doing temp=temp->next half of current capacity times" }, { "code": null, "e": 35555, "s": 35483, "text": "Now Insert the element x between temp and temp->next by relinking nodes" }, { "code": null, "e": 35585, "s": 35555, "text": "Increment the capacity by one" }, { "code": null, "e": 35805, "s": 35585, "text": "pop__front() If the capacity of size is less than 1 then return -1Otherwise, delete the first node between the head and head->next nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element" }, { "code": null, "e": 35859, "s": 35805, "text": "If the capacity of size is less than 1 then return -1" }, { "code": null, "e": 35949, "s": 35859, "text": "Otherwise, delete the first node between the head and head->next nodes by relinking nodes" }, { "code": null, "e": 35979, "s": 35949, "text": "Decrement the capacity by one" }, { "code": null, "e": 36015, "s": 35979, "text": "Return value of the deleted element" }, { "code": null, "e": 36229, "s": 36015, "text": "pop__back(): If the capacity is less than 1 then return -1Otherwise, delete the end node between the last and last->previous nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element" }, { "code": null, "e": 36275, "s": 36229, "text": "If the capacity is less than 1 then return -1" }, { "code": null, "e": 36367, "s": 36275, "text": "Otherwise, delete the end node between the last and last->previous nodes by relinking nodes" }, { "code": null, "e": 36397, "s": 36367, "text": "Decrement the capacity by one" }, { "code": null, "e": 36433, "s": 36397, "text": "Return value of the deleted element" }, { "code": null, "e": 36740, "s": 36433, "text": "pop__middle(): Initialize a temp pointer of type nodeReach the middle element of the doubly linked list by doing temp=temp->next half of current capacity timesNow delete temp node between temp->previous and temp->next nodes by relinking nodesDecrement the capacity by oneReturn value of the deleted element" }, { "code": null, "e": 36779, "s": 36740, "text": "Initialize a temp pointer of type node" }, { "code": null, "e": 36886, "s": 36779, "text": "Reach the middle element of the doubly linked list by doing temp=temp->next half of current capacity times" }, { "code": null, "e": 36970, "s": 36886, "text": "Now delete temp node between temp->previous and temp->next nodes by relinking nodes" }, { "code": null, "e": 37000, "s": 36970, "text": "Decrement the capacity by one" }, { "code": null, "e": 37036, "s": 37000, "text": "Return value of the deleted element" }, { "code": null, "e": 37055, "s": 37036, "text": "surindertarika1234" }, { "code": null, "e": 37064, "s": 37055, "text": "gabaa406" }, { "code": null, "e": 37074, "s": 37064, "text": "cpp-queue" }, { "code": null, "e": 37078, "s": 37074, "text": "STL" }, { "code": null, "e": 37090, "s": 37078, "text": "Linked List" }, { "code": null, "e": 37096, "s": 37090, "text": "Queue" }, { "code": null, "e": 37108, "s": 37096, "text": "Linked List" }, { "code": null, "e": 37114, "s": 37108, "text": "Queue" }, { "code": null, "e": 37118, "s": 37114, "text": "STL" }, { "code": null, "e": 37216, "s": 37118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37225, "s": 37216, "text": "Comments" }, { "code": null, "e": 37238, "s": 37225, "text": "Old Comments" }, { "code": null, "e": 37288, "s": 37238, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 37326, "s": 37288, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 37366, "s": 37326, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 37437, "s": 37366, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 37478, "s": 37437, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 37518, "s": 37478, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 37552, "s": 37518, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 37568, "s": 37552, "text": "Queue in Python" }, { "code": null, "e": 37592, "s": 37568, "text": "Queue Interface In Java" } ]