title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Program to print multiplication table of any number in PHP - GeeksforGeeks
27 Oct, 2021 In this article, we will see how to print the multiplication table of any given number using PHP. To make the multiplication table, first, we get a number input from the user and then use for loop to display the multiplication table. We use HTML and PHP to display the multiplication table. The HTML part is used to design a form to get the input from the user and the PHP part is used to execute the multiplication and display the results in table format. Example: PHP <!DOCTYPE html><html> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> Program to print multiplication<br> table of any number in PHP </h3> <form method="POST"> Enter a number: <input type="text" name="number"> <input type="Submit" value="Get Multiplication Table"> </form> </center></body> </html> <?phpif($_POST) { $num = $_POST["number"]; echo nl2br("<p style='text-align: center;'> Multiplication Table of $num: </p> "); for ($i = 1; $i <= 10; $i++) { echo ("<p style='text-align: center;'>$num" . " X " . "$i" . " = " . $num * $i . "</p> "); }}?> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions loop PHP-math PHP-Questions HTML PHP Web Technologies HTML PHP 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 ? How to Insert Form Data into Database using PHP ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Advantages and Disadvantages of PHP How to Upload Image into Database and Display it using PHP ? PHP | Converting string to Date and DateTime How to check whether an array is empty using PHP? Best way to initialize empty array in PHP
[ { "code": null, "e": 26035, "s": 26007, "text": "\n27 Oct, 2021" }, { "code": null, "e": 26269, "s": 26035, "text": "In this article, we will see how to print the multiplication table of any given number using PHP. To make the multiplication table, first, we get a number input from the user and then use for loop to display the multiplication table." }, { "code": null, "e": 26492, "s": 26269, "text": "We use HTML and PHP to display the multiplication table. The HTML part is used to design a form to get the input from the user and the PHP part is used to execute the multiplication and display the results in table format." }, { "code": null, "e": 26501, "s": 26492, "text": "Example:" }, { "code": null, "e": 26505, "s": 26501, "text": "PHP" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> Program to print multiplication<br> table of any number in PHP </h3> <form method=\"POST\"> Enter a number: <input type=\"text\" name=\"number\"> <input type=\"Submit\" value=\"Get Multiplication Table\"> </form> </center></body> </html> <?phpif($_POST) { $num = $_POST[\"number\"]; echo nl2br(\"<p style='text-align: center;'> Multiplication Table of $num: </p> \"); for ($i = 1; $i <= 10; $i++) { echo (\"<p style='text-align: center;'>$num\" . \" X \" . \"$i\" . \" = \" . $num * $i . \"</p> \"); }}?>", "e": 27299, "s": 26505, "text": null }, { "code": null, "e": 27307, "s": 27299, "text": "Output:" }, { "code": null, "e": 27444, "s": 27307, "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": 27459, "s": 27444, "text": "HTML-Questions" }, { "code": null, "e": 27464, "s": 27459, "text": "loop" }, { "code": null, "e": 27473, "s": 27464, "text": "PHP-math" }, { "code": null, "e": 27487, "s": 27473, "text": "PHP-Questions" }, { "code": null, "e": 27492, "s": 27487, "text": "HTML" }, { "code": null, "e": 27496, "s": 27492, "text": "PHP" }, { "code": null, "e": 27513, "s": 27496, "text": "Web Technologies" }, { "code": null, "e": 27518, "s": 27513, "text": "HTML" }, { "code": null, "e": 27522, "s": 27518, "text": "PHP" }, { "code": null, "e": 27620, "s": 27522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27668, "s": 27620, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27718, "s": 27668, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27742, "s": 27718, "text": "REST API (Introduction)" }, { "code": null, "e": 27792, "s": 27742, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27829, "s": 27792, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27865, "s": 27829, "text": "Advantages and Disadvantages of PHP" }, { "code": null, "e": 27926, "s": 27865, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27971, "s": 27926, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28021, "s": 27971, "text": "How to check whether an array is empty using PHP?" } ]
Python PIL | ImageChops.screen() and ImageChops.offset() method - GeeksforGeeks
22 Jun, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. This method is used to superimpose two inverted images on top of each other. Syntax: ImageChops.screen(image1, image2) Parameters: image1 first image image2 second image Return Value: An Image Python3 # This will import Image and ImageChops modulesfrom PIL import Image, ImageChops # Opening Imagesim = Image.open(r"C:\Users\Admin\Pictures\images.png")im2 = Image.open(r"C:\Users\Admin\Pictures\download.PNG") # superimposing images im and im2im3 = ImageChops.screen(im, im2) # showing resultant imageim3.show() Output: This method returns a copy of the image where data has been offset by the given distances. Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset. Syntax: ImageChops.offset(image1, xoffset, yoffset = None)Parameters: image: It is the image on which offset is provided xoffset: the horizontal distance yoffset: it is the vertical distance, if omitted both distance are set to same.Return value: Copy of the original image Python3 # This will import Image and ImageChops modulesfrom PIL import Image, ImageChops # Opening Imagesim = Image.open(r"C:\Users\Admin\Pictures\images.png")im2 = Image.open(r"C:\Users\Admin\Pictures\download.PNG") # Here, xoffset is given 100# yoffset wil automatically set to 100im3 = ImageChops.offset(im, 140) # showing resultant imageim3.show() Output: simranarora5sos Image-Processing python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25771, "s": 25743, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25877, "s": 25771, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. " }, { "code": null, "e": 25955, "s": 25877, "text": "This method is used to superimpose two inverted images on top of each other. " }, { "code": null, "e": 26073, "s": 25955, "text": "Syntax: ImageChops.screen(image1, image2)\n\nParameters:\nimage1 first image\nimage2 second image\n\nReturn Value: An Image" }, { "code": null, "e": 26083, "s": 26075, "text": "Python3" }, { "code": "# This will import Image and ImageChops modulesfrom PIL import Image, ImageChops # Opening Imagesim = Image.open(r\"C:\\Users\\Admin\\Pictures\\images.png\")im2 = Image.open(r\"C:\\Users\\Admin\\Pictures\\download.PNG\") # superimposing images im and im2im3 = ImageChops.screen(im, im2) # showing resultant imageim3.show()", "e": 26394, "s": 26083, "text": null }, { "code": null, "e": 26404, "s": 26394, "text": "Output: " }, { "code": null, "e": 26588, "s": 26406, "text": "This method returns a copy of the image where data has been offset by the given distances. Data wraps around the edges. If yoffset is omitted, it is assumed to be equal to xoffset. " }, { "code": null, "e": 26864, "s": 26588, "text": "Syntax: ImageChops.offset(image1, xoffset, yoffset = None)Parameters: image: It is the image on which offset is provided xoffset: the horizontal distance yoffset: it is the vertical distance, if omitted both distance are set to same.Return value: Copy of the original image " }, { "code": null, "e": 26874, "s": 26866, "text": "Python3" }, { "code": "# This will import Image and ImageChops modulesfrom PIL import Image, ImageChops # Opening Imagesim = Image.open(r\"C:\\Users\\Admin\\Pictures\\images.png\")im2 = Image.open(r\"C:\\Users\\Admin\\Pictures\\download.PNG\") # Here, xoffset is given 100# yoffset wil automatically set to 100im3 = ImageChops.offset(im, 140) # showing resultant imageim3.show()", "e": 27218, "s": 26874, "text": null }, { "code": null, "e": 27228, "s": 27218, "text": "Output: " }, { "code": null, "e": 27246, "s": 27230, "text": "simranarora5sos" }, { "code": null, "e": 27263, "s": 27246, "text": "Image-Processing" }, { "code": null, "e": 27278, "s": 27263, "text": "python-utility" }, { "code": null, "e": 27285, "s": 27278, "text": "Python" }, { "code": null, "e": 27383, "s": 27285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27401, "s": 27383, "text": "Python Dictionary" }, { "code": null, "e": 27436, "s": 27401, "text": "Read a file line by line in Python" }, { "code": null, "e": 27468, "s": 27436, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27490, "s": 27468, "text": "Enumerate() in Python" }, { "code": null, "e": 27532, "s": 27490, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27562, "s": 27532, "text": "Iterate over a list in Python" }, { "code": null, "e": 27588, "s": 27562, "text": "Python String | replace()" }, { "code": null, "e": 27617, "s": 27588, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27661, "s": 27617, "text": "Reading and Writing to text files in Python" } ]
CSS transform Property - GeeksforGeeks
01 Nov, 2021 The transform property in CSS is used to change the coordinate space of the visual formatting model. This is used to add effects like skew, rotate, translate, etc on elements. Syntax: transform: none|transform-functions|initial|inherit; Note: The transformations can be of 2-D or 3-D type. Values: none: No transformation takes place. matrix(x, x, x, x, x, x): It specifies a matrix transformation of 2-D type. It takes 6 values. matrix3d(x, x, x, x, x, x, x, x, x): It specifies a matrix transformation of 3-D type. It takes 9 values. translate(x, y): It specifies a translation across the X and Y axes. translate3d(x, y, z): It specifies a translation across the X, Y, and Z axes. translateX(x): It specifies the translation across the X-axis only. translateY(y): It specifies the translation across the Y-axis only. translateZ(z): It specifies the translation across the Z-axis only. rotate(angle): It specifies the angle of rotation. rotateX(angle): It specifies the rotation along with the X-axis corresponding to the angle of rotation. roatateY(angle): It specifies the rotation along with the Y-axis corresponding to the angle of rotation. roteteZ(angle): It specifies the rotation along with the Z-axis corresponding to the angle of rotation. scale(x, y): It specifies the scale transformation along the X and Y axes. scale3d(x, y, z): It specifies the scale transformation along the X, Y, and Z axes. scaleX(x): It specifies the scale transformation along the X-axis. scaleY(y): It specifies the scale transformation along the Y-axis. scaleZ(z): It specifies the scale transformation along the Z-axis. scale3d(x, y, z): It specifies the scale transformation along the X, Y, and Z axes. skew(angle, angle): It specifies the skew transformation along the X and Y axes corresponding to the skew angles. skewX(angle): It specifies the skew transformation along with the X-axis corresponding to the skew angle. skewY(angle): It specifies the skew transformation along with the Y-axis corresponding to the skew angle. skewZ(angle): It specifies the skew transformation along with the Z-axis corresponding to the skew angle. perspective(x): It specifies the perspective of an element. Refer: Perspective property initial: It initializes the element to its default value. inherit: It inherits the value from its parent element. Example 1: Without the transform property. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 2: This example describes Matrix() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: matrix(1, 0, -1, 1, 1, 0); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 3: This example describes Matrix3d() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; transform-style: preserve-3d; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform-style: preserve-3d; position: absolute; transform: translate(150px, 75%, 5em) } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 4: This example describes translate() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translate(150px, 65%); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 5: This example describes translate3d() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translate(150px, 65%, 5em); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 6: This example describes translateX() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateX(150px); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 7: This example describes translateY() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateY(150px); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 8: This example describes translateZ() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateZ(150px); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 9: This example describes rotate() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotate(45deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 10: This example describes rotateX() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateX(75deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 11: This example describes rotateY() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateY(75deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 12: This example describes rotateZ() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateZ(75deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 13: This example describes scale() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scale(1, 2); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 14: This example describes scale3d() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scale3d(2, 1, 5); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 15: This example describes scaleX() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleX(2); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 16: This example describes scaleY() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleY(2); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 17: This example describes scaleZ() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleZ(2); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 18: This example describes skew() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skew(30deg, 30deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 19: This example describes skewX() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skewX(30deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 20: This example describes skewY() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skewY(30deg); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 21: This example describes perspective() property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: perspective(30px); } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 22: This example describes the initial property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: initial; } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Example 23: This example describes inherit property value. HTML <!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; transform: rotateX(45deg); } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: inherit; } </style></head> <body> <div class="main"> <div class="GFG">GeeksforGeeks</div> </div></body></html> Output: Note: Sometimes the 3-D values don’t give the correct output when they are used on 2-D elements, Hence it is not recommended to use 3-D values for 2-D elements. Supported Browsers: The browser supported by transform property are listed below: 2-D Transforms: Chrome 36.0, 4.0 -webkit-Edge 10.0, 9.0 -ms-Firefox 16.0, 3.5 -moz-Safari 9.0, 3.2 -webkit-Opera 23.0, 15.0 -webkit-, 10.5 -o- Chrome 36.0, 4.0 -webkit- Edge 10.0, 9.0 -ms- Firefox 16.0, 3.5 -moz- Safari 9.0, 3.2 -webkit- Opera 23.0, 15.0 -webkit-, 10.5 -o- 3-D Transforms: Chrome 36.0, 12.0 -webkit-Edge 12.0Firefox 10.0Safari 9.0, 4.0 -webkit-Opera 23.0, 15.0 -webkit- Chrome 36.0, 12.0 -webkit- Edge 12.0 Firefox 10.0 Safari 9.0, 4.0 -webkit- Opera 23.0, 15.0 -webkit- bhaskargeeksforgeeks CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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": 24955, "s": 24927, "text": "\n01 Nov, 2021" }, { "code": null, "e": 25131, "s": 24955, "text": "The transform property in CSS is used to change the coordinate space of the visual formatting model. This is used to add effects like skew, rotate, translate, etc on elements." }, { "code": null, "e": 25139, "s": 25131, "text": "Syntax:" }, { "code": null, "e": 25192, "s": 25139, "text": "transform: none|transform-functions|initial|inherit;" }, { "code": null, "e": 25245, "s": 25192, "text": "Note: The transformations can be of 2-D or 3-D type." }, { "code": null, "e": 25253, "s": 25245, "text": "Values:" }, { "code": null, "e": 25290, "s": 25253, "text": "none: No transformation takes place." }, { "code": null, "e": 25385, "s": 25290, "text": "matrix(x, x, x, x, x, x): It specifies a matrix transformation of 2-D type. It takes 6 values." }, { "code": null, "e": 25491, "s": 25385, "text": "matrix3d(x, x, x, x, x, x, x, x, x): It specifies a matrix transformation of 3-D type. It takes 9 values." }, { "code": null, "e": 25560, "s": 25491, "text": "translate(x, y): It specifies a translation across the X and Y axes." }, { "code": null, "e": 25638, "s": 25560, "text": "translate3d(x, y, z): It specifies a translation across the X, Y, and Z axes." }, { "code": null, "e": 25706, "s": 25638, "text": "translateX(x): It specifies the translation across the X-axis only." }, { "code": null, "e": 25774, "s": 25706, "text": "translateY(y): It specifies the translation across the Y-axis only." }, { "code": null, "e": 25842, "s": 25774, "text": "translateZ(z): It specifies the translation across the Z-axis only." }, { "code": null, "e": 25893, "s": 25842, "text": "rotate(angle): It specifies the angle of rotation." }, { "code": null, "e": 25997, "s": 25893, "text": "rotateX(angle): It specifies the rotation along with the X-axis corresponding to the angle of rotation." }, { "code": null, "e": 26102, "s": 25997, "text": "roatateY(angle): It specifies the rotation along with the Y-axis corresponding to the angle of rotation." }, { "code": null, "e": 26206, "s": 26102, "text": "roteteZ(angle): It specifies the rotation along with the Z-axis corresponding to the angle of rotation." }, { "code": null, "e": 26281, "s": 26206, "text": "scale(x, y): It specifies the scale transformation along the X and Y axes." }, { "code": null, "e": 26365, "s": 26281, "text": "scale3d(x, y, z): It specifies the scale transformation along the X, Y, and Z axes." }, { "code": null, "e": 26432, "s": 26365, "text": "scaleX(x): It specifies the scale transformation along the X-axis." }, { "code": null, "e": 26499, "s": 26432, "text": "scaleY(y): It specifies the scale transformation along the Y-axis." }, { "code": null, "e": 26566, "s": 26499, "text": "scaleZ(z): It specifies the scale transformation along the Z-axis." }, { "code": null, "e": 26650, "s": 26566, "text": "scale3d(x, y, z): It specifies the scale transformation along the X, Y, and Z axes." }, { "code": null, "e": 26764, "s": 26650, "text": "skew(angle, angle): It specifies the skew transformation along the X and Y axes corresponding to the skew angles." }, { "code": null, "e": 26870, "s": 26764, "text": "skewX(angle): It specifies the skew transformation along with the X-axis corresponding to the skew angle." }, { "code": null, "e": 26976, "s": 26870, "text": "skewY(angle): It specifies the skew transformation along with the Y-axis corresponding to the skew angle." }, { "code": null, "e": 27082, "s": 26976, "text": "skewZ(angle): It specifies the skew transformation along with the Z-axis corresponding to the skew angle." }, { "code": null, "e": 27170, "s": 27082, "text": "perspective(x): It specifies the perspective of an element. Refer: Perspective property" }, { "code": null, "e": 27228, "s": 27170, "text": "initial: It initializes the element to its default value." }, { "code": null, "e": 27284, "s": 27228, "text": "inherit: It inherits the value from its parent element." }, { "code": null, "e": 27327, "s": 27284, "text": "Example 1: Without the transform property." }, { "code": null, "e": 27332, "s": 27327, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 27746, "s": 27332, "text": null }, { "code": null, "e": 27754, "s": 27746, "text": "Output:" }, { "code": null, "e": 27814, "s": 27754, "text": "Example 2: This example describes Matrix() property value. " }, { "code": null, "e": 27819, "s": 27814, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: matrix(1, 0, -1, 1, 1, 0); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 28278, "s": 27819, "text": null }, { "code": null, "e": 28286, "s": 28278, "text": "Output:" }, { "code": null, "e": 28347, "s": 28286, "text": "Example 3: This example describes Matrix3d() property value." }, { "code": null, "e": 28352, "s": 28347, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; transform-style: preserve-3d; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform-style: preserve-3d; position: absolute; transform: translate(150px, 75%, 5em) } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 28912, "s": 28352, "text": null }, { "code": null, "e": 28920, "s": 28912, "text": "Output:" }, { "code": null, "e": 28982, "s": 28920, "text": "Example 4: This example describes translate() property value." }, { "code": null, "e": 28987, "s": 28982, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translate(150px, 65%); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 29442, "s": 28987, "text": null }, { "code": null, "e": 29450, "s": 29442, "text": "Output:" }, { "code": null, "e": 29514, "s": 29450, "text": "Example 5: This example describes translate3d() property value." }, { "code": null, "e": 29519, "s": 29514, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translate(150px, 65%, 5em); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 29979, "s": 29519, "text": null }, { "code": null, "e": 29987, "s": 29979, "text": "Output:" }, { "code": null, "e": 30050, "s": 29987, "text": "Example 6: This example describes translateX() property value." }, { "code": null, "e": 30055, "s": 30050, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateX(150px); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 30506, "s": 30055, "text": null }, { "code": null, "e": 30514, "s": 30506, "text": "Output:" }, { "code": null, "e": 30578, "s": 30514, "text": "Example 7: This example describes translateY() property value. " }, { "code": null, "e": 30583, "s": 30578, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateY(150px); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 31034, "s": 30583, "text": null }, { "code": null, "e": 31042, "s": 31034, "text": "Output:" }, { "code": null, "e": 31105, "s": 31042, "text": "Example 8: This example describes translateZ() property value." }, { "code": null, "e": 31110, "s": 31105, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: translateZ(150px); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 31561, "s": 31110, "text": null }, { "code": null, "e": 31569, "s": 31561, "text": "Output:" }, { "code": null, "e": 31628, "s": 31569, "text": "Example 9: This example describes rotate() property value." }, { "code": null, "e": 31633, "s": 31628, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotate(45deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 32080, "s": 31633, "text": null }, { "code": null, "e": 32088, "s": 32080, "text": "Output:" }, { "code": null, "e": 32149, "s": 32088, "text": "Example 10: This example describes rotateX() property value." }, { "code": null, "e": 32154, "s": 32149, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateX(75deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 32602, "s": 32154, "text": null }, { "code": null, "e": 32610, "s": 32602, "text": "Output:" }, { "code": null, "e": 32671, "s": 32610, "text": "Example 11: This example describes rotateY() property value." }, { "code": null, "e": 32676, "s": 32671, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateY(75deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 33124, "s": 32676, "text": null }, { "code": null, "e": 33133, "s": 33124, "text": "Output: " }, { "code": null, "e": 33194, "s": 33133, "text": "Example 12: This example describes rotateZ() property value." }, { "code": null, "e": 33199, "s": 33194, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: rotateZ(75deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 33647, "s": 33199, "text": null }, { "code": null, "e": 33655, "s": 33647, "text": "Output:" }, { "code": null, "e": 33714, "s": 33655, "text": "Example 13: This example describes scale() property value." }, { "code": null, "e": 33719, "s": 33714, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scale(1, 2); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 34164, "s": 33719, "text": null }, { "code": null, "e": 34172, "s": 34164, "text": "Output:" }, { "code": null, "e": 34233, "s": 34172, "text": "Example 14: This example describes scale3d() property value." }, { "code": null, "e": 34238, "s": 34233, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scale3d(2, 1, 5); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 34688, "s": 34238, "text": null }, { "code": null, "e": 34696, "s": 34688, "text": "Output:" }, { "code": null, "e": 34756, "s": 34696, "text": "Example 15: This example describes scaleX() property value." }, { "code": null, "e": 34761, "s": 34756, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleX(2); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 35204, "s": 34761, "text": null }, { "code": null, "e": 35212, "s": 35204, "text": "Output:" }, { "code": null, "e": 35272, "s": 35212, "text": "Example 16: This example describes scaleY() property value." }, { "code": null, "e": 35277, "s": 35272, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleY(2); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 35720, "s": 35277, "text": null }, { "code": null, "e": 35728, "s": 35720, "text": "Output:" }, { "code": null, "e": 35788, "s": 35728, "text": "Example 17: This example describes scaleZ() property value." }, { "code": null, "e": 35793, "s": 35788, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: scaleZ(2); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 36236, "s": 35793, "text": null }, { "code": null, "e": 36244, "s": 36236, "text": "Output:" }, { "code": null, "e": 36302, "s": 36244, "text": "Example 18: This example describes skew() property value." }, { "code": null, "e": 36307, "s": 36302, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skew(30deg, 30deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 36759, "s": 36307, "text": null }, { "code": null, "e": 36767, "s": 36759, "text": "Output:" }, { "code": null, "e": 36826, "s": 36767, "text": "Example 19: This example describes skewX() property value." }, { "code": null, "e": 36831, "s": 36826, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skewX(30deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 37277, "s": 36831, "text": null }, { "code": null, "e": 37285, "s": 37277, "text": "Output:" }, { "code": null, "e": 37344, "s": 37285, "text": "Example 20: This example describes skewY() property value." }, { "code": null, "e": 37349, "s": 37344, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: skewY(30deg); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 37795, "s": 37349, "text": null }, { "code": null, "e": 37803, "s": 37795, "text": "Output:" }, { "code": null, "e": 37868, "s": 37803, "text": "Example 21: This example describes perspective() property value." }, { "code": null, "e": 37873, "s": 37868, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: perspective(30px); } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 38324, "s": 37873, "text": null }, { "code": null, "e": 38332, "s": 38324, "text": "Output:" }, { "code": null, "e": 38395, "s": 38332, "text": "Example 22: This example describes the initial property value." }, { "code": null, "e": 38400, "s": 38395, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: initial; } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 38841, "s": 38400, "text": null }, { "code": null, "e": 38849, "s": 38841, "text": "Output:" }, { "code": null, "e": 38909, "s": 38849, "text": "Example 23: This example describes inherit property value. " }, { "code": null, "e": 38914, "s": 38909, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> CSS Transform Property </title> <style> .main { display: grid; padding: 30px; background-color: green; transform: rotateX(45deg); } .GFG { text-align: center; font-size: 35px; background-color: white; color: green; transform: inherit; } </style></head> <body> <div class=\"main\"> <div class=\"GFG\">GeeksforGeeks</div> </div></body></html>", "e": 39389, "s": 38914, "text": null }, { "code": null, "e": 39397, "s": 39389, "text": "Output:" }, { "code": null, "e": 39559, "s": 39397, "text": "Note: Sometimes the 3-D values don’t give the correct output when they are used on 2-D elements, Hence it is not recommended to use 3-D values for 2-D elements. " }, { "code": null, "e": 39641, "s": 39559, "text": "Supported Browsers: The browser supported by transform property are listed below:" }, { "code": null, "e": 39784, "s": 39641, "text": "2-D Transforms: Chrome 36.0, 4.0 -webkit-Edge 10.0, 9.0 -ms-Firefox 16.0, 3.5 -moz-Safari 9.0, 3.2 -webkit-Opera 23.0, 15.0 -webkit-, 10.5 -o-" }, { "code": null, "e": 39810, "s": 39784, "text": "Chrome 36.0, 4.0 -webkit-" }, { "code": null, "e": 39830, "s": 39810, "text": "Edge 10.0, 9.0 -ms-" }, { "code": null, "e": 39854, "s": 39830, "text": "Firefox 16.0, 3.5 -moz-" }, { "code": null, "e": 39879, "s": 39854, "text": "Safari 9.0, 3.2 -webkit-" }, { "code": null, "e": 39915, "s": 39879, "text": "Opera 23.0, 15.0 -webkit-, 10.5 -o-" }, { "code": null, "e": 40028, "s": 39915, "text": "3-D Transforms: Chrome 36.0, 12.0 -webkit-Edge 12.0Firefox 10.0Safari 9.0, 4.0 -webkit-Opera 23.0, 15.0 -webkit-" }, { "code": null, "e": 40055, "s": 40028, "text": "Chrome 36.0, 12.0 -webkit-" }, { "code": null, "e": 40065, "s": 40055, "text": "Edge 12.0" }, { "code": null, "e": 40078, "s": 40065, "text": "Firefox 10.0" }, { "code": null, "e": 40103, "s": 40078, "text": "Safari 9.0, 4.0 -webkit-" }, { "code": null, "e": 40129, "s": 40103, "text": "Opera 23.0, 15.0 -webkit-" }, { "code": null, "e": 40150, "s": 40129, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 40165, "s": 40150, "text": "CSS-Properties" }, { "code": null, "e": 40172, "s": 40165, "text": "Picked" }, { "code": null, "e": 40176, "s": 40172, "text": "CSS" }, { "code": null, "e": 40193, "s": 40176, "text": "Web Technologies" }, { "code": null, "e": 40291, "s": 40193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40341, "s": 40291, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 40403, "s": 40341, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40451, "s": 40403, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40509, "s": 40451, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 40564, "s": 40509, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40604, "s": 40564, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40637, "s": 40604, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40682, "s": 40637, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40725, "s": 40682, "text": "How to fetch data from an API in ReactJS ?" } ]
Merge Sort - GeeksforGeeks
22 Apr, 2022 Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then it merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See the following C implementation for details. MergeSort(arr[], l, r) If r > l 1. Find the middle point to divide the array into two halves: middle m = l+ (r-l)/2 2. Call mergeSort for first half: Call mergeSort(arr, l, m) 3. Call mergeSort for second half: Call mergeSort(arr, m+1, r) 4. Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r) The following diagram from wikipedia shows the complete merge sort process for an example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively divided into two halves till the size becomes 1. Once the size becomes 1, the merge processes come into action and start merging arrays back till the complete array is merged. C++ C Java Python3 C# Javascript // C++ program for Merge Sort#include <iostream>using namespace std; // Merges two subarrays of array[].// First subarray is arr[begin..mid]// Second subarray is arr[mid+1..end]void merge(int array[], int const left, int const mid, int const right){ auto const subArrayOne = mid - left + 1; auto const subArrayTwo = right - mid; // Create temp arrays auto *leftArray = new int[subArrayOne], *rightArray = new int[subArrayTwo]; // Copy data to temp arrays leftArray[] and rightArray[] for (auto i = 0; i < subArrayOne; i++) leftArray[i] = array[left + i]; for (auto j = 0; j < subArrayTwo; j++) rightArray[j] = array[mid + 1 + j]; auto indexOfSubArrayOne = 0, // Initial index of first sub-array indexOfSubArrayTwo = 0; // Initial index of second sub-array int indexOfMergedArray = left; // Initial index of merged array // Merge the temp arrays back into array[left..right] while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; } else { array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; } indexOfMergedArray++; } // Copy the remaining elements of // left[], if there are any while (indexOfSubArrayOne < subArrayOne) { array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; indexOfMergedArray++; } // Copy the remaining elements of // right[], if there are any while (indexOfSubArrayTwo < subArrayTwo) { array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; indexOfMergedArray++; }} // begin is for left index and end is// right index of the sub-array// of arr to be sorted */void mergeSort(int array[], int const begin, int const end){ if (begin >= end) return; // Returns recursively auto mid = begin + (end - begin) / 2; mergeSort(array, begin, mid); mergeSort(array, mid + 1, end); merge(array, begin, mid, end);} // UTILITY FUNCTIONS// Function to print an arrayvoid printArray(int A[], int size){ for (auto i = 0; i < size; i++) cout << A[i] << " ";} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; auto arr_size = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); cout << "\nSorted array is \n"; printArray(arr, arr_size); return 0;} // This code is contributed by Mayank Tyagi// This code was revised by Joshua Estes /* C program for Merge Sort */#include <stdio.h>#include <stdlib.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver code */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0;} /* Java program for Merge Sort */class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarray array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m =l+ (r-l)/2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver code public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6, 7 }; System.out.println("Given Array"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length - 1); System.out.println("\nSorted array"); printArray(arr); }}/* This code is contributed by Rajat Mishra */ # Python program for implementation of MergeSortdef mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end=" ") print() # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print("Given array is", end="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end="\n") printList(arr) # This code is contributed by Mayank Khanna // C# program for Merge Sortusing System;class MergeSort { // Merges two subarrays of []arr. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int[] arr, int l, int m, int r) { // Find sizes of two // subarrays to be merged int n1 = m - l + 1; int n2 = r - m; // Create temp arrays int[] L = new int[n1]; int[] R = new int[n2]; int i, j; // Copy data to temp arrays for (i = 0; i < n1; ++i) L[i] = arr[l + i]; for (j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; // Merge the temp arrays // Initial indexes of first // and second subarrays i = 0; j = 0; // Initial index of merged // subarray array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy remaining elements // of L[] if any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy remaining elements // of R[] if any while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that // sorts arr[l..r] using // merge() void sort(int[] arr, int l, int r) { if (l < r) { // Find the middle // point int m = l+ (r-l)/2; // Sort first and // second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } // A utility function to // print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver code public static void Main(String[] args) { int[] arr = { 12, 11, 13, 5, 6, 7 }; Console.WriteLine("Given Array"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.Length - 1); Console.WriteLine("\nSorted array"); printArray(arr); }} // This code is contributed by Princi Singh <script> // JavaScript program for Merge Sort // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]function merge(arr, l, m, r){ var n1 = m - l + 1; var n2 = r - m; // Create temp arrays var L = new Array(n1); var R = new Array(n2); // Copy data to temp arrays L[] and R[] for (var i = 0; i < n1; i++) L[i] = arr[l + i]; for (var j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; // Merge the temp arrays back into arr[l..r] // Initial index of first subarray var i = 0; // Initial index of second subarray var j = 0; // Initial index of merged subarray var k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements of // L[], if there are any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements of // R[], if there are any while (j < n2) { arr[k] = R[j]; j++; k++; }} // l is for left index and r is// right index of the sub-array// of arr to be sorted */function mergeSort(arr,l, r){ if(l>=r){ return;//returns recursively } var m =l+ parseInt((r-l)/2); mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r);} // UTILITY FUNCTIONS// Function to print an arrayfunction printArray( A, size){ for (var i = 0; i < size; i++) document.write( A[i] + " ");} var arr = [ 12, 11, 13, 5, 6, 7 ]; var arr_size = arr.length; document.write( "Given array is <br>"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); document.write( "<br>Sorted array is <br>"); printArray(arr, arr_size); // This code is contributed by SoumikMondal </script> Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13 Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + θ(n) The above recurrence can be solved either using the Recurrence Tree method or the Master method. It falls in case II of Master Method and the solution of the recurrence is θ(nLogn). Time complexity of Merge Sort is θ(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.Auxiliary Space: O(n)Algorithmic Paradigm: Divide and ConquerSorting In Place: No in a typical implementationStable: Yes Applications of Merge Sort Merge Sort is useful for sorting linked lists in O(nLogn) time. In the case of linked lists, the case is different mainly due to the difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike an array, in the linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can be implemented without extra space for linked lists.In arrays, we can do random access as elements are contiguous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in the linked list. Quick Sort requires a lot of this kind of access. In a linked list to access i’th index, we have to travel each and every node from the head to i’th node as we don’t have a continuous block of memory. Therefore, the overhead increases for quicksort. Merge sort accesses data sequentially and the need of random access is low.Inversion Count ProblemUsed in External Sorting Merge Sort is useful for sorting linked lists in O(nLogn) time. In the case of linked lists, the case is different mainly due to the difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike an array, in the linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can be implemented without extra space for linked lists.In arrays, we can do random access as elements are contiguous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in the linked list. Quick Sort requires a lot of this kind of access. In a linked list to access i’th index, we have to travel each and every node from the head to i’th node as we don’t have a continuous block of memory. Therefore, the overhead increases for quicksort. Merge sort accesses data sequentially and the need of random access is low. Inversion Count Problem Used in External Sorting Drawbacks of Merge Sort Slower comparative to the other sort algorithms for smaller tasks. Merge sort algorithm requires an additional memory space of 0(n) for the temporary array. It goes through the whole process even if the array is sorted. YouTubeGeeksforGeeks507K subscribersMerge Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=JSceec-wEyw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Recent Articles on Merge Sort Coding practice for sorting. Quiz on Merge Sort Other Sorting Algorithms on GeeksforGeeks: 3-way Merge Sort, Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb SortPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp khanna98 pineconelam jnjomnsn mayanktyagi1709 princi singh naveenkuma150 vishalg2 akkkkk sidhijain SoumikMondal sagepup0620 pranay20228 as5853535 sumitgumber28 Amazon Boomerang Commerce Goldman Sachs Grofers Microsoft Oracle Paytm Qualcomm Snapdeal Target Corporation Divide and Conquer Sorting Paytm Amazon Microsoft Snapdeal Oracle Goldman Sachs Qualcomm Boomerang Commerce Grofers Target Corporation Divide and Conquer Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array Bubble Sort Insertion Sort Selection Sort std::sort() in C++ STL Time Complexities of all Sorting Algorithms
[ { "code": null, "e": 25399, "s": 25371, "text": "\n22 Apr, 2022" }, { "code": null, "e": 25824, "s": 25399, "text": "Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then it merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See the following C implementation for details." }, { "code": null, "e": 26214, "s": 25824, "text": "MergeSort(arr[], l, r)\nIf r > l\n 1. Find the middle point to divide the array into two halves: \n middle m = l+ (r-l)/2\n 2. Call mergeSort for first half: \n Call mergeSort(arr, l, m)\n 3. Call mergeSort for second half:\n Call mergeSort(arr, m+1, r)\n 4. Merge the two halves sorted in step 2 and 3:\n Call merge(arr, l, m, r)" }, { "code": null, "e": 26597, "s": 26214, "text": "The following diagram from wikipedia shows the complete merge sort process for an example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively divided into two halves till the size becomes 1. Once the size becomes 1, the merge processes come into action and start merging arrays back till the complete array is merged. " }, { "code": null, "e": 26603, "s": 26599, "text": "C++" }, { "code": null, "e": 26605, "s": 26603, "text": "C" }, { "code": null, "e": 26610, "s": 26605, "text": "Java" }, { "code": null, "e": 26618, "s": 26610, "text": "Python3" }, { "code": null, "e": 26621, "s": 26618, "text": "C#" }, { "code": null, "e": 26632, "s": 26621, "text": "Javascript" }, { "code": "// C++ program for Merge Sort#include <iostream>using namespace std; // Merges two subarrays of array[].// First subarray is arr[begin..mid]// Second subarray is arr[mid+1..end]void merge(int array[], int const left, int const mid, int const right){ auto const subArrayOne = mid - left + 1; auto const subArrayTwo = right - mid; // Create temp arrays auto *leftArray = new int[subArrayOne], *rightArray = new int[subArrayTwo]; // Copy data to temp arrays leftArray[] and rightArray[] for (auto i = 0; i < subArrayOne; i++) leftArray[i] = array[left + i]; for (auto j = 0; j < subArrayTwo; j++) rightArray[j] = array[mid + 1 + j]; auto indexOfSubArrayOne = 0, // Initial index of first sub-array indexOfSubArrayTwo = 0; // Initial index of second sub-array int indexOfMergedArray = left; // Initial index of merged array // Merge the temp arrays back into array[left..right] while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; } else { array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; } indexOfMergedArray++; } // Copy the remaining elements of // left[], if there are any while (indexOfSubArrayOne < subArrayOne) { array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; indexOfSubArrayOne++; indexOfMergedArray++; } // Copy the remaining elements of // right[], if there are any while (indexOfSubArrayTwo < subArrayTwo) { array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; indexOfSubArrayTwo++; indexOfMergedArray++; }} // begin is for left index and end is// right index of the sub-array// of arr to be sorted */void mergeSort(int array[], int const begin, int const end){ if (begin >= end) return; // Returns recursively auto mid = begin + (end - begin) / 2; mergeSort(array, begin, mid); mergeSort(array, mid + 1, end); merge(array, begin, mid, end);} // UTILITY FUNCTIONS// Function to print an arrayvoid printArray(int A[], int size){ for (auto i = 0; i < size; i++) cout << A[i] << \" \";} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; auto arr_size = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is \\n\"; printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); cout << \"\\nSorted array is \\n\"; printArray(arr, arr_size); return 0;} // This code is contributed by Mayank Tyagi// This code was revised by Joshua Estes", "e": 29390, "s": 26632, "text": null }, { "code": "/* C program for Merge Sort */#include <stdio.h>#include <stdlib.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", A[i]); printf(\"\\n\");} /* Driver code */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf(\"Given array is \\n\"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf(\"\\nSorted array is \\n\"); printArray(arr, arr_size); return 0;}", "e": 31389, "s": 29390, "text": null }, { "code": "/* Java program for Merge Sort */class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarray array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m =l+ (r-l)/2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver code public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6, 7 }; System.out.println(\"Given Array\"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length - 1); System.out.println(\"\\nSorted array\"); printArray(arr); }}/* This code is contributed by Rajat Mishra */", "e": 33686, "s": 31389, "text": null }, { "code": "# Python program for implementation of MergeSortdef mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end=\" \") print() # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print(\"Given array is\", end=\"\\n\") printList(arr) mergeSort(arr) print(\"Sorted array is: \", end=\"\\n\") printList(arr) # This code is contributed by Mayank Khanna", "e": 34917, "s": 33686, "text": null }, { "code": "// C# program for Merge Sortusing System;class MergeSort { // Merges two subarrays of []arr. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int[] arr, int l, int m, int r) { // Find sizes of two // subarrays to be merged int n1 = m - l + 1; int n2 = r - m; // Create temp arrays int[] L = new int[n1]; int[] R = new int[n2]; int i, j; // Copy data to temp arrays for (i = 0; i < n1; ++i) L[i] = arr[l + i]; for (j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; // Merge the temp arrays // Initial indexes of first // and second subarrays i = 0; j = 0; // Initial index of merged // subarray array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy remaining elements // of L[] if any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy remaining elements // of R[] if any while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that // sorts arr[l..r] using // merge() void sort(int[] arr, int l, int r) { if (l < r) { // Find the middle // point int m = l+ (r-l)/2; // Sort first and // second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } // A utility function to // print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver code public static void Main(String[] args) { int[] arr = { 12, 11, 13, 5, 6, 7 }; Console.WriteLine(\"Given Array\"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.Length - 1); Console.WriteLine(\"\\nSorted array\"); printArray(arr); }} // This code is contributed by Princi Singh", "e": 37301, "s": 34917, "text": null }, { "code": "<script> // JavaScript program for Merge Sort // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]function merge(arr, l, m, r){ var n1 = m - l + 1; var n2 = r - m; // Create temp arrays var L = new Array(n1); var R = new Array(n2); // Copy data to temp arrays L[] and R[] for (var i = 0; i < n1; i++) L[i] = arr[l + i]; for (var j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; // Merge the temp arrays back into arr[l..r] // Initial index of first subarray var i = 0; // Initial index of second subarray var j = 0; // Initial index of merged subarray var k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements of // L[], if there are any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements of // R[], if there are any while (j < n2) { arr[k] = R[j]; j++; k++; }} // l is for left index and r is// right index of the sub-array// of arr to be sorted */function mergeSort(arr,l, r){ if(l>=r){ return;//returns recursively } var m =l+ parseInt((r-l)/2); mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r);} // UTILITY FUNCTIONS// Function to print an arrayfunction printArray( A, size){ for (var i = 0; i < size; i++) document.write( A[i] + \" \");} var arr = [ 12, 11, 13, 5, 6, 7 ]; var arr_size = arr.length; document.write( \"Given array is <br>\"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); document.write( \"<br>Sorted array is <br>\"); printArray(arr, arr_size); // This code is contributed by SoumikMondal </script>", "e": 39189, "s": 37301, "text": null }, { "code": null, "e": 39253, "s": 39189, "text": "Given array is \n12 11 13 5 6 7 \nSorted array is \n5 6 7 11 12 13" }, { "code": null, "e": 39437, "s": 39253, "text": "Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + θ(n)" }, { "code": null, "e": 39921, "s": 39437, "text": "The above recurrence can be solved either using the Recurrence Tree method or the Master method. It falls in case II of Master Method and the solution of the recurrence is θ(nLogn). Time complexity of Merge Sort is θ(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.Auxiliary Space: O(n)Algorithmic Paradigm: Divide and ConquerSorting In Place: No in a typical implementationStable: Yes" }, { "code": null, "e": 39949, "s": 39921, "text": "Applications of Merge Sort " }, { "code": null, "e": 41071, "s": 39949, "text": "Merge Sort is useful for sorting linked lists in O(nLogn) time. In the case of linked lists, the case is different mainly due to the difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike an array, in the linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can be implemented without extra space for linked lists.In arrays, we can do random access as elements are contiguous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in the linked list. Quick Sort requires a lot of this kind of access. In a linked list to access i’th index, we have to travel each and every node from the head to i’th node as we don’t have a continuous block of memory. Therefore, the overhead increases for quicksort. Merge sort accesses data sequentially and the need of random access is low.Inversion Count ProblemUsed in External Sorting" }, { "code": null, "e": 42146, "s": 41071, "text": "Merge Sort is useful for sorting linked lists in O(nLogn) time. In the case of linked lists, the case is different mainly due to the difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike an array, in the linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can be implemented without extra space for linked lists.In arrays, we can do random access as elements are contiguous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in the linked list. Quick Sort requires a lot of this kind of access. In a linked list to access i’th index, we have to travel each and every node from the head to i’th node as we don’t have a continuous block of memory. Therefore, the overhead increases for quicksort. Merge sort accesses data sequentially and the need of random access is low." }, { "code": null, "e": 42170, "s": 42146, "text": "Inversion Count Problem" }, { "code": null, "e": 42195, "s": 42170, "text": "Used in External Sorting" }, { "code": null, "e": 42219, "s": 42195, "text": "Drawbacks of Merge Sort" }, { "code": null, "e": 42286, "s": 42219, "text": "Slower comparative to the other sort algorithms for smaller tasks." }, { "code": null, "e": 42376, "s": 42286, "text": "Merge sort algorithm requires an additional memory space of 0(n) for the temporary array." }, { "code": null, "e": 42439, "s": 42376, "text": "It goes through the whole process even if the array is sorted." }, { "code": null, "e": 43248, "s": 42439, "text": "YouTubeGeeksforGeeks507K subscribersMerge Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=JSceec-wEyw\" 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": 43278, "s": 43248, "text": "Recent Articles on Merge Sort" }, { "code": null, "e": 43307, "s": 43278, "text": "Coding practice for sorting." }, { "code": null, "e": 43326, "s": 43307, "text": "Quiz on Merge Sort" }, { "code": null, "e": 43651, "s": 43326, "text": "Other Sorting Algorithms on GeeksforGeeks: 3-way Merge Sort, Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb SortPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 43657, "s": 43651, "text": "ukasp" }, { "code": null, "e": 43666, "s": 43657, "text": "khanna98" }, { "code": null, "e": 43678, "s": 43666, "text": "pineconelam" }, { "code": null, "e": 43687, "s": 43678, "text": "jnjomnsn" }, { "code": null, "e": 43703, "s": 43687, "text": "mayanktyagi1709" }, { "code": null, "e": 43716, "s": 43703, "text": "princi singh" }, { "code": null, "e": 43730, "s": 43716, "text": "naveenkuma150" }, { "code": null, "e": 43739, "s": 43730, "text": "vishalg2" }, { "code": null, "e": 43746, "s": 43739, "text": "akkkkk" }, { "code": null, "e": 43756, "s": 43746, "text": "sidhijain" }, { "code": null, "e": 43769, "s": 43756, "text": "SoumikMondal" }, { "code": null, "e": 43781, "s": 43769, "text": "sagepup0620" }, { "code": null, "e": 43793, "s": 43781, "text": "pranay20228" }, { "code": null, "e": 43803, "s": 43793, "text": "as5853535" }, { "code": null, "e": 43817, "s": 43803, "text": "sumitgumber28" }, { "code": null, "e": 43824, "s": 43817, "text": "Amazon" }, { "code": null, "e": 43843, "s": 43824, "text": "Boomerang Commerce" }, { "code": null, "e": 43857, "s": 43843, "text": "Goldman Sachs" }, { "code": null, "e": 43865, "s": 43857, "text": "Grofers" }, { "code": null, "e": 43875, "s": 43865, "text": "Microsoft" }, { "code": null, "e": 43882, "s": 43875, "text": "Oracle" }, { "code": null, "e": 43888, "s": 43882, "text": "Paytm" }, { "code": null, "e": 43897, "s": 43888, "text": "Qualcomm" }, { "code": null, "e": 43906, "s": 43897, "text": "Snapdeal" }, { "code": null, "e": 43925, "s": 43906, "text": "Target Corporation" }, { "code": null, "e": 43944, "s": 43925, "text": "Divide and Conquer" }, { "code": null, "e": 43952, "s": 43944, "text": "Sorting" }, { "code": null, "e": 43958, "s": 43952, "text": "Paytm" }, { "code": null, "e": 43965, "s": 43958, "text": "Amazon" }, { "code": null, "e": 43975, "s": 43965, "text": "Microsoft" }, { "code": null, "e": 43984, "s": 43975, "text": "Snapdeal" }, { "code": null, "e": 43991, "s": 43984, "text": "Oracle" }, { "code": null, "e": 44005, "s": 43991, "text": "Goldman Sachs" }, { "code": null, "e": 44014, "s": 44005, "text": "Qualcomm" }, { "code": null, "e": 44033, "s": 44014, "text": "Boomerang Commerce" }, { "code": null, "e": 44041, "s": 44033, "text": "Grofers" }, { "code": null, "e": 44060, "s": 44041, "text": "Target Corporation" }, { "code": null, "e": 44079, "s": 44060, "text": "Divide and Conquer" }, { "code": null, "e": 44087, "s": 44079, "text": "Sorting" }, { "code": null, "e": 44185, "s": 44087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44212, "s": 44185, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 44256, "s": 44212, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 44303, "s": 44256, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 44341, "s": 44303, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 44402, "s": 44341, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 44414, "s": 44402, "text": "Bubble Sort" }, { "code": null, "e": 44429, "s": 44414, "text": "Insertion Sort" }, { "code": null, "e": 44444, "s": 44429, "text": "Selection Sort" }, { "code": null, "e": 44467, "s": 44444, "text": "std::sort() in C++ STL" } ]
Index Mapping (or Trivial Hashing) with negatives allowed - GeeksforGeeks
20 Jul, 2021 Given a limited range array contains both positive and non-positive numbers, i.e., elements are in the range from -MAX to +MAX. Our task is to search if some number is present in the array or not in O(1) time.Since range is limited, we can use index mapping (or trivial hashing). We use values as the index in a big array. Therefore we can search and insert elements in O(1) time. How to handle negative numbers? The idea is to use a 2D array of size hash[MAX+1][2]Algorithm: Assign all the values of the hash matrix as 0. Traverse the given array: If the element ele is non negative assign hash[ele][0] as 1. Else take the absolute value of ele and assign hash[ele][1] as 1. To search any element x in the array. If X is non-negative check if hash[X][0] is 1 or not. If hash[X][0] is one then the number is present else not present. If X is negative take absolute value of X and then check if hash[X][1] is 1 or not. If hash[X][1] is one then the number is present Below is the implementation of the above idea. C++ Java Python3 C# Javascript // CPP program to implement direct index mapping// with negative values allowed.#include <bits/stdc++.h>using namespace std;#define MAX 1000 // Since array is global, it is initialized as 0.bool has[MAX + 1][2]; // searching if X is Present in the given array // or not.bool search(int X){ if (X >= 0) { if (has[X][0] == 1) return true; else return false; } // if X is negative take the absolute // value of X. X = abs(X); if (has[X][1] == 1) return true; return false;} void insert(int a[], int n){ for (int i = 0; i < n; i++) { if (a[i] >= 0) has[a[i]][0] = 1; else has[abs(a[i])][1] = 1; }} // Driver codeint main(){ int a[] = { -1, 9, -5, -8, -5, -2 }; int n = sizeof(a)/sizeof(a[0]); insert(a, n); int X = -5; if (search(X) == true) cout << "Present"; else cout << "Not Present"; return 0;} // Java program to implement direct index // mapping with negative values allowed. class GFG{ final static int MAX = 1000; // Since array is global, it // is initialized as 0. static boolean[][] has = new boolean[MAX + 1][2]; // searching if X is Present in // the given array or not. static boolean search(int X) { if (X >= 0) { if (has[X][0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.abs(X); if (has[X][1] == true) { return true; } return false;} static void insert(int a[], int n) { for (int i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i]][0] = true; } else { int abs_i = Math.Abs(a[i]); has[abs_i][1] = true; } }} // Driver code public static void main(String args[]) { int a[] = {-1, 9, -5, -8, -5, -2}; int n = a.length; insert(a, n); int X = -5; if (search(X) == true) { System.out.println("Present"); } else { System.out.println("Not Present"); }}} // This code is contributed// by 29AjayKumar # Python3 program to implement direct index # mapping with negative values allowed. # Searching if X is Present in the # given array or not.def search(X): if X >= 0: return has[X][0] == 1 # if X is negative take the absolute # value of X. X = abs(X) return has[X][1] == 1 def insert(a, n): for i in range(0, n): if a[i] >= 0: has[a[i]][0] = 1 else: has[abs(a[i])][1] = 1 # Driver codeif __name__ == "__main__": a = [-1, 9, -5, -8, -5, -2] n = len(a) MAX = 1000 # Since array is global, it is # initialized as 0. has = [[0 for i in range(2)] for j in range(MAX + 1)] insert(a, n) X = -5 if search(X) == True: print("Present") else: print("Not Present") # This code is contributed by Rituraj Jain // C# program to implement direct index // mapping with negative values allowed. using System; class GFG{ static int MAX = 1000; // Since array is global, it // is initialized as 0. static bool[,] has = new bool[MAX + 1, 2]; // searching if X is Present in // the given array or not. static bool search(int X) { if (X >= 0) { if (has[X, 0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.Abs(X); if (has[X, 1] == true) { return true; } return false;} static void insert(int[] a, int n) { for (int i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i], 0] = true; } else { int abs_i = Math.Abs(a[i]); has[abs_i, 1] = true; } }} // Driver code public static void Main() { int[] a = {-1, 9, -5, -8, -5, -2}; int n = a.Length; insert(a, n); int X = -5; if (search(X) == true) { Console.WriteLine("Present"); } else { Console.WriteLine("Not Present"); }}} // This code is contributed// by Akanksha Rai <script> // JavaScript program to implement direct index // mapping with negative values allowed. let MAX = 1000; // Since array is global, it // is initialized as 0. let has = new Array(MAX+1);for(let i=0;i<MAX+1;i++){ has[i]=new Array(2); for(let j=0;j<2;j++) has[i][j]=0;} // searching if X is Present in // the given array or not.function search(X){ if (X >= 0) { if (has[X][0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.abs(X); if (has[X][1] == true) { return true; } return false; } function insert(a,n){ for (let i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i]][0] = true; } else { int abs_i = Math.abs(a[i]); has[abs_i][1] = true; } }} // Driver code let a=[-1, 9, -5, -8, -5, -2];let n = a.length; insert(a, n); let X = -5; if (search(X) == true) { document.write("Present"); } else { document.write("Not Present"); } // This code is contributed by rag2127 </script> Output: Present This article is contributed by ShivamKD. 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. fsociety_|_ 29AjayKumar Akanksha_Rai rituraj_jain noob_programmer RahulKumar182 rag2127 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 Largest Sum Contiguous Subarray Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Linear Search Internal Working of HashMap in Java Count pairs with given sum Sort string of characters Counting frequencies of array elements Most frequent element in an array
[ { "code": null, "e": 39003, "s": 38975, "text": "\n20 Jul, 2021" }, { "code": null, "e": 39385, "s": 39003, "text": "Given a limited range array contains both positive and non-positive numbers, i.e., elements are in the range from -MAX to +MAX. Our task is to search if some number is present in the array or not in O(1) time.Since range is limited, we can use index mapping (or trivial hashing). We use values as the index in a big array. Therefore we can search and insert elements in O(1) time. " }, { "code": null, "e": 39480, "s": 39385, "text": "How to handle negative numbers? The idea is to use a 2D array of size hash[MAX+1][2]Algorithm:" }, { "code": null, "e": 39707, "s": 39480, "text": "Assign all the values of the hash matrix as 0.\nTraverse the given array:\n If the element ele is non negative assign \n hash[ele][0] as 1.\n Else take the absolute value of ele and \n assign hash[ele][1] as 1." }, { "code": null, "e": 39747, "s": 39707, "text": "To search any element x in the array. " }, { "code": null, "e": 39867, "s": 39747, "text": "If X is non-negative check if hash[X][0] is 1 or not. If hash[X][0] is one then the number is present else not present." }, { "code": null, "e": 39999, "s": 39867, "text": "If X is negative take absolute value of X and then check if hash[X][1] is 1 or not. If hash[X][1] is one then the number is present" }, { "code": null, "e": 40048, "s": 39999, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 40052, "s": 40048, "text": "C++" }, { "code": null, "e": 40057, "s": 40052, "text": "Java" }, { "code": null, "e": 40065, "s": 40057, "text": "Python3" }, { "code": null, "e": 40068, "s": 40065, "text": "C#" }, { "code": null, "e": 40079, "s": 40068, "text": "Javascript" }, { "code": "// CPP program to implement direct index mapping// with negative values allowed.#include <bits/stdc++.h>using namespace std;#define MAX 1000 // Since array is global, it is initialized as 0.bool has[MAX + 1][2]; // searching if X is Present in the given array // or not.bool search(int X){ if (X >= 0) { if (has[X][0] == 1) return true; else return false; } // if X is negative take the absolute // value of X. X = abs(X); if (has[X][1] == 1) return true; return false;} void insert(int a[], int n){ for (int i = 0; i < n; i++) { if (a[i] >= 0) has[a[i]][0] = 1; else has[abs(a[i])][1] = 1; }} // Driver codeint main(){ int a[] = { -1, 9, -5, -8, -5, -2 }; int n = sizeof(a)/sizeof(a[0]); insert(a, n); int X = -5; if (search(X) == true) cout << \"Present\"; else cout << \"Not Present\"; return 0;}", "e": 41024, "s": 40079, "text": null }, { "code": "// Java program to implement direct index // mapping with negative values allowed. class GFG{ final static int MAX = 1000; // Since array is global, it // is initialized as 0. static boolean[][] has = new boolean[MAX + 1][2]; // searching if X is Present in // the given array or not. static boolean search(int X) { if (X >= 0) { if (has[X][0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.abs(X); if (has[X][1] == true) { return true; } return false;} static void insert(int a[], int n) { for (int i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i]][0] = true; } else { int abs_i = Math.Abs(a[i]); has[abs_i][1] = true; } }} // Driver code public static void main(String args[]) { int a[] = {-1, 9, -5, -8, -5, -2}; int n = a.length; insert(a, n); int X = -5; if (search(X) == true) { System.out.println(\"Present\"); } else { System.out.println(\"Not Present\"); }}} // This code is contributed// by 29AjayKumar", "e": 42249, "s": 41024, "text": null }, { "code": "# Python3 program to implement direct index # mapping with negative values allowed. # Searching if X is Present in the # given array or not.def search(X): if X >= 0: return has[X][0] == 1 # if X is negative take the absolute # value of X. X = abs(X) return has[X][1] == 1 def insert(a, n): for i in range(0, n): if a[i] >= 0: has[a[i]][0] = 1 else: has[abs(a[i])][1] = 1 # Driver codeif __name__ == \"__main__\": a = [-1, 9, -5, -8, -5, -2] n = len(a) MAX = 1000 # Since array is global, it is # initialized as 0. has = [[0 for i in range(2)] for j in range(MAX + 1)] insert(a, n) X = -5 if search(X) == True: print(\"Present\") else: print(\"Not Present\") # This code is contributed by Rituraj Jain", "e": 43085, "s": 42249, "text": null }, { "code": "// C# program to implement direct index // mapping with negative values allowed. using System; class GFG{ static int MAX = 1000; // Since array is global, it // is initialized as 0. static bool[,] has = new bool[MAX + 1, 2]; // searching if X is Present in // the given array or not. static bool search(int X) { if (X >= 0) { if (has[X, 0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.Abs(X); if (has[X, 1] == true) { return true; } return false;} static void insert(int[] a, int n) { for (int i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i], 0] = true; } else { int abs_i = Math.Abs(a[i]); has[abs_i, 1] = true; } }} // Driver code public static void Main() { int[] a = {-1, 9, -5, -8, -5, -2}; int n = a.Length; insert(a, n); int X = -5; if (search(X) == true) { Console.WriteLine(\"Present\"); } else { Console.WriteLine(\"Not Present\"); }}} // This code is contributed// by Akanksha Rai", "e": 44294, "s": 43085, "text": null }, { "code": "<script> // JavaScript program to implement direct index // mapping with negative values allowed. let MAX = 1000; // Since array is global, it // is initialized as 0. let has = new Array(MAX+1);for(let i=0;i<MAX+1;i++){ has[i]=new Array(2); for(let j=0;j<2;j++) has[i][j]=0;} // searching if X is Present in // the given array or not.function search(X){ if (X >= 0) { if (has[X][0] == true) { return true; } else { return false; } } // if X is negative take the // absolute value of X. X = Math.abs(X); if (has[X][1] == true) { return true; } return false; } function insert(a,n){ for (let i = 0; i < n; i++) { if (a[i] >= 0) { has[a[i]][0] = true; } else { int abs_i = Math.abs(a[i]); has[abs_i][1] = true; } }} // Driver code let a=[-1, 9, -5, -8, -5, -2];let n = a.length; insert(a, n); let X = -5; if (search(X) == true) { document.write(\"Present\"); } else { document.write(\"Not Present\"); } // This code is contributed by rag2127 </script>", "e": 45510, "s": 44294, "text": null }, { "code": null, "e": 45520, "s": 45510, "text": "Output: " }, { "code": null, "e": 45528, "s": 45520, "text": "Present" }, { "code": null, "e": 45945, "s": 45528, "text": "This article is contributed by ShivamKD. 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": 45957, "s": 45945, "text": "fsociety_|_" }, { "code": null, "e": 45969, "s": 45957, "text": "29AjayKumar" }, { "code": null, "e": 45982, "s": 45969, "text": "Akanksha_Rai" }, { "code": null, "e": 45995, "s": 45982, "text": "rituraj_jain" }, { "code": null, "e": 46011, "s": 45995, "text": "noob_programmer" }, { "code": null, "e": 46025, "s": 46011, "text": "RahulKumar182" }, { "code": null, "e": 46033, "s": 46025, "text": "rag2127" }, { "code": null, "e": 46040, "s": 46033, "text": "Arrays" }, { "code": null, "e": 46045, "s": 46040, "text": "Hash" }, { "code": null, "e": 46052, "s": 46045, "text": "Arrays" }, { "code": null, "e": 46057, "s": 46052, "text": "Hash" }, { "code": null, "e": 46155, "s": 46057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46223, "s": 46155, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 46255, "s": 46223, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 46299, "s": 46255, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 46331, "s": 46299, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 46345, "s": 46331, "text": "Linear Search" }, { "code": null, "e": 46381, "s": 46345, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 46408, "s": 46381, "text": "Count pairs with given sum" }, { "code": null, "e": 46434, "s": 46408, "text": "Sort string of characters" }, { "code": null, "e": 46473, "s": 46434, "text": "Counting frequencies of array elements" } ]
How to find the length of an Array in C# - GeeksforGeeks
11 Oct, 2019 Array.Length Property is used to get the total number of elements in all the dimensions of the Array. Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array. Syntax: public int Length { get; } Property Value: This property returns the total number of elements in all the dimensions of the Array. It can also return zero if there are no elements in the array. The return type is System.Int32. Exception: This property throws the OverflowException if the array is multidimensional and contains more than MaxValue elements. Here MaxValue is 2147483647. Below programs illustrate the use of above-discussed property: Example 1: // C# program to find the// the total number of// elements in 1-D Arrayusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares a 1D Array of string. string[] weekDays; // allocating memory for days. weekDays = new string[] {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // Displaying Elements of the array foreach(string day in weekDays) Console.Write(day + " "); Console.Write("\nTotal Number of Elements: "); // using Length property Console.Write(weekDays.Length); }}} Sun Mon Tue Wed Thu Fri Sat Total Number of Elements: 7 Example 2: // C# program to find the total// number of elements in the// multidimensional Arraysusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; // The same array with dimensions // specified 4 row and 2 column. int[, ] intarray_d = new int[4, 2] {{ 1, 2}, {3, 4}, {5, 6}, {7, 8}}; // Three-dimensional array. int[,, ] intarray3D = new int[,, ] {{{ 1, 2, 3}, { 4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}}; // The same array with dimensions // specified 2, 2 and 3. int[,, ] intarray3Dd = new int[2, 2, 3] {{{1, 2, 3}, {4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}}; Console.Write("Total Number of Elements in intarray: "); // using Length property Console.Write(intarray.Length); Console.Write("\nTotal Number of Elements in intarray_d: "); // using Length property Console.Write(intarray_d.Length); Console.Write("\nTotal Number of Elements in intarray3D: "); // using Length property Console.Write(intarray3D.Length); Console.Write("\nTotal Number of Elements in intarray3Dd: "); // using Length property Console.Write(intarray3Dd.Length); }}} Total Number of Elements in intarray: 8 Total Number of Elements in intarray_d: 8 Total Number of Elements in intarray3D: 12 Total Number of Elements in intarray3Dd: 12 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.length?view=netframework-4.7.2 Akanksha_Rai CSharp-Arrays 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# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 26337, "s": 26309, "text": "\n11 Oct, 2019" }, { "code": null, "e": 26565, "s": 26337, "text": "Array.Length Property is used to get the total number of elements in all the dimensions of the Array. Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array." }, { "code": null, "e": 26573, "s": 26565, "text": "Syntax:" }, { "code": null, "e": 26600, "s": 26573, "text": "public int Length { get; }" }, { "code": null, "e": 26799, "s": 26600, "text": "Property Value: This property returns the total number of elements in all the dimensions of the Array. It can also return zero if there are no elements in the array. The return type is System.Int32." }, { "code": null, "e": 26957, "s": 26799, "text": "Exception: This property throws the OverflowException if the array is multidimensional and contains more than MaxValue elements. Here MaxValue is 2147483647." }, { "code": null, "e": 27020, "s": 26957, "text": "Below programs illustrate the use of above-discussed property:" }, { "code": null, "e": 27031, "s": 27020, "text": "Example 1:" }, { "code": "// C# program to find the// the total number of// elements in 1-D Arrayusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares a 1D Array of string. string[] weekDays; // allocating memory for days. weekDays = new string[] {\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"}; // Displaying Elements of the array foreach(string day in weekDays) Console.Write(day + \" \"); Console.Write(\"\\nTotal Number of Elements: \"); // using Length property Console.Write(weekDays.Length); }}}", "e": 27694, "s": 27031, "text": null }, { "code": null, "e": 27752, "s": 27694, "text": "Sun Mon Tue Wed Thu Fri Sat \nTotal Number of Elements: 7\n" }, { "code": null, "e": 27763, "s": 27752, "text": "Example 2:" }, { "code": "// C# program to find the total// number of elements in the// multidimensional Arraysusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; // The same array with dimensions // specified 4 row and 2 column. int[, ] intarray_d = new int[4, 2] {{ 1, 2}, {3, 4}, {5, 6}, {7, 8}}; // Three-dimensional array. int[,, ] intarray3D = new int[,, ] {{{ 1, 2, 3}, { 4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}}; // The same array with dimensions // specified 2, 2 and 3. int[,, ] intarray3Dd = new int[2, 2, 3] {{{1, 2, 3}, {4, 5, 6}}, {{ 7, 8, 9}, {10, 11, 12}}}; Console.Write(\"Total Number of Elements in intarray: \"); // using Length property Console.Write(intarray.Length); Console.Write(\"\\nTotal Number of Elements in intarray_d: \"); // using Length property Console.Write(intarray_d.Length); Console.Write(\"\\nTotal Number of Elements in intarray3D: \"); // using Length property Console.Write(intarray3D.Length); Console.Write(\"\\nTotal Number of Elements in intarray3Dd: \"); // using Length property Console.Write(intarray3Dd.Length); }}}", "e": 29632, "s": 27763, "text": null }, { "code": null, "e": 29802, "s": 29632, "text": "Total Number of Elements in intarray: 8\nTotal Number of Elements in intarray_d: 8\nTotal Number of Elements in intarray3D: 12\nTotal Number of Elements in intarray3Dd: 12\n" }, { "code": null, "e": 29813, "s": 29802, "text": "Reference:" }, { "code": null, "e": 29901, "s": 29813, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.length?view=netframework-4.7.2" }, { "code": null, "e": 29914, "s": 29901, "text": "Akanksha_Rai" }, { "code": null, "e": 29928, "s": 29914, "text": "CSharp-Arrays" }, { "code": null, "e": 29931, "s": 29928, "text": "C#" }, { "code": null, "e": 30029, "s": 29931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30057, "s": 30029, "text": "C# Dictionary with examples" }, { "code": null, "e": 30072, "s": 30057, "text": "C# | Delegates" }, { "code": null, "e": 30095, "s": 30072, "text": "C# | Method Overriding" }, { "code": null, "e": 30117, "s": 30095, "text": "C# | Abstract Classes" }, { "code": null, "e": 30163, "s": 30117, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30186, "s": 30163, "text": "Extension Method in C#" }, { "code": null, "e": 30208, "s": 30186, "text": "C# | Class and Object" }, { "code": null, "e": 30226, "s": 30208, "text": "C# | Constructors" }, { "code": null, "e": 30266, "s": 30226, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Perl | References - GeeksforGeeks
10 Oct, 2018 In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values which are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type which holds the location of another variable. Another variable can be scalar, hashes, arrays, function name etc. Nested data structure can be created easily as a user can create a list which contains the references to another list that can further contain the references to arrays, scalar or hashes etc. You can create references for scalar value, hash, array, function etc. In order to create a reference, define a new scalar variable and assign it the name of the variable(whose reference you want to create) by prefixing it with a backslash. Examples: Making References of different Data Types: # Array Reference # defining array @array = ('1', '2', '3'); # making reference of array variable $reference_array = \@array; # Hash Reference # defining hash %hash = ('1'=>'a', '2'=>'b', '3'=>'c'); # make reference of the hash variable $reference_hash = \%hash; # Scalar Value Reference # defining scalar $scalar_val = 1234; # making reference of scalar variable $reference_scalar = \$scalar_val; Note: A reference to an anonymous hash can be created using the curly brackets {} around the key and value pairs.Example:# creating reference to anonymous hash $ref_to_anonymous_hash = {'GFG' => '1', 'Geeks' => '2'}; Example: # creating reference to anonymous hash $ref_to_anonymous_hash = {'GFG' => '1', 'Geeks' => '2'}; A reference to an anonymous array can be created using the square brackets [].Example:# creating reference to an anonymous array $ref_to_anonymous_array = [20, 30, ['G', 'F', 'G']]; Example: # creating reference to an anonymous array $ref_to_anonymous_array = [20, 30, ['G', 'F', 'G']]; A reference to an anonymous subroutine can also be created with the help of sub. Here there will be no name for the sub.Example:# creating reference to an anonymous subroutine $ref_to_anonymous_subroutine = sub { print "GeeksforGeeks\n"}; Example: # creating reference to an anonymous subroutine $ref_to_anonymous_subroutine = sub { print "GeeksforGeeks\n"}; A reference to an Input/output handle i.e. dirhandle and filehandle cannot be created. Now, after we have made the reference, we need to use it to access the value. Dereferencing is the way of accessing the value in the memory pointed by the reference. In order to dereference, we use the prefix $, @, % or & depending on the type of the variable(a reference can point to a array, scalar, or hash etc). Example 1: # Perl program to illustrate the # Dereferencing of an Array # defining an array@array = ('1', '2', '3'); # making an reference to an array variable$reference_array = \@array; # Dereferencing# printing the value stored # at $reference_array by prefixing # @ as it is a array referenceprint @$reference_array; 123 Example 2: # Perl program to illustrate the # Dereferencing of a Hash # defining hash%hash = ('1'=>'a', '2'=>'b', '3'=>'c'); # creating an reference to hash variable$reference_hash = \%hash; # Dereferencing# printing the value stored # at $reference_hash by prefixing # % as it is a hash referenceprint %$reference_hash; 3c2b1a Example 3: # Perl program to illustrate the # Dereferencing of a Scalar # defining a scalar$scalar = 1234; # creating an reference to scalar variable $reference_scalar = \$scalar; # Dereferencing# printing the value stored # at $reference_scalar by prefixing # $ as it is a Scalar referenceprint $$reference_scalar; 1234 Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Multidimensional Hashes Perl | Opening and Reading a File Perl | ne operator Perl | Scope of Variables Perl | Hashes Perl | Data Types Perl | defined() Function
[ { "code": null, "e": 25315, "s": 25287, "text": "\n10 Oct, 2018" }, { "code": null, "e": 25933, "s": 25315, "text": "In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values which are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type which holds the location of another variable. Another variable can be scalar, hashes, arrays, function name etc. Nested data structure can be created easily as a user can create a list which contains the references to another list that can further contain the references to arrays, scalar or hashes etc." }, { "code": null, "e": 26174, "s": 25933, "text": "You can create references for scalar value, hash, array, function etc. In order to create a reference, define a new scalar variable and assign it the name of the variable(whose reference you want to create) by prefixing it with a backslash." }, { "code": null, "e": 26227, "s": 26174, "text": "Examples: Making References of different Data Types:" }, { "code": null, "e": 26361, "s": 26227, "text": "# Array Reference\n\n# defining array \n@array = ('1', '2', '3');\n\n# making reference of array variable \n$reference_array = \\@array; \n" }, { "code": null, "e": 26505, "s": 26361, "text": "# Hash Reference\n\n# defining hash\n%hash = ('1'=>'a', '2'=>'b', '3'=>'c'); \n\n# make reference of the hash variable\n$reference_hash = \\%hash; \n" }, { "code": null, "e": 26645, "s": 26505, "text": "# Scalar Value Reference\n\n# defining scalar\n$scalar_val = 1234;\n \n# making reference of scalar variable\n$reference_scalar = \\$scalar_val; \n" }, { "code": null, "e": 26651, "s": 26645, "text": "Note:" }, { "code": null, "e": 26863, "s": 26651, "text": "A reference to an anonymous hash can be created using the curly brackets {} around the key and value pairs.Example:# creating reference to anonymous hash\n$ref_to_anonymous_hash = {'GFG' => '1', 'Geeks' => '2'};\n" }, { "code": null, "e": 26872, "s": 26863, "text": "Example:" }, { "code": null, "e": 26969, "s": 26872, "text": "# creating reference to anonymous hash\n$ref_to_anonymous_hash = {'GFG' => '1', 'Geeks' => '2'};\n" }, { "code": null, "e": 27152, "s": 26969, "text": "A reference to an anonymous array can be created using the square brackets [].Example:# creating reference to an anonymous array\n$ref_to_anonymous_array = [20, 30, ['G', 'F', 'G']];\n" }, { "code": null, "e": 27161, "s": 27152, "text": "Example:" }, { "code": null, "e": 27258, "s": 27161, "text": "# creating reference to an anonymous array\n$ref_to_anonymous_array = [20, 30, ['G', 'F', 'G']];\n" }, { "code": null, "e": 27498, "s": 27258, "text": "A reference to an anonymous subroutine can also be created with the help of sub. Here there will be no name for the sub.Example:# creating reference to an anonymous subroutine\n$ref_to_anonymous_subroutine = sub { print \"GeeksforGeeks\\n\"};\n" }, { "code": null, "e": 27507, "s": 27498, "text": "Example:" }, { "code": null, "e": 27619, "s": 27507, "text": "# creating reference to an anonymous subroutine\n$ref_to_anonymous_subroutine = sub { print \"GeeksforGeeks\\n\"};\n" }, { "code": null, "e": 27706, "s": 27619, "text": "A reference to an Input/output handle i.e. dirhandle and filehandle cannot be created." }, { "code": null, "e": 28022, "s": 27706, "text": "Now, after we have made the reference, we need to use it to access the value. Dereferencing is the way of accessing the value in the memory pointed by the reference. In order to dereference, we use the prefix $, @, % or & depending on the type of the variable(a reference can point to a array, scalar, or hash etc)." }, { "code": null, "e": 28033, "s": 28022, "text": "Example 1:" }, { "code": "# Perl program to illustrate the # Dereferencing of an Array # defining an array@array = ('1', '2', '3'); # making an reference to an array variable$reference_array = \\@array; # Dereferencing# printing the value stored # at $reference_array by prefixing # @ as it is a array referenceprint @$reference_array; ", "e": 28353, "s": 28033, "text": null }, { "code": null, "e": 28358, "s": 28353, "text": "123\n" }, { "code": null, "e": 28369, "s": 28358, "text": "Example 2:" }, { "code": "# Perl program to illustrate the # Dereferencing of a Hash # defining hash%hash = ('1'=>'a', '2'=>'b', '3'=>'c'); # creating an reference to hash variable$reference_hash = \\%hash; # Dereferencing# printing the value stored # at $reference_hash by prefixing # % as it is a hash referenceprint %$reference_hash; ", "e": 28687, "s": 28369, "text": null }, { "code": null, "e": 28695, "s": 28687, "text": "3c2b1a\n" }, { "code": null, "e": 28706, "s": 28695, "text": "Example 3:" }, { "code": "# Perl program to illustrate the # Dereferencing of a Scalar # defining a scalar$scalar = 1234; # creating an reference to scalar variable $reference_scalar = \\$scalar; # Dereferencing# printing the value stored # at $reference_scalar by prefixing # $ as it is a Scalar referenceprint $$reference_scalar; ", "e": 29017, "s": 28706, "text": null }, { "code": null, "e": 29023, "s": 29017, "text": "1234\n" }, { "code": null, "e": 29028, "s": 29023, "text": "Perl" }, { "code": null, "e": 29033, "s": 29028, "text": "Perl" }, { "code": null, "e": 29131, "s": 29033, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29172, "s": 29131, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29210, "s": 29172, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 29237, "s": 29210, "text": "Perl | Inheritance in OOPs" }, { "code": null, "e": 29268, "s": 29237, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 29302, "s": 29268, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 29321, "s": 29302, "text": "Perl | ne operator" }, { "code": null, "e": 29347, "s": 29321, "text": "Perl | Scope of Variables" }, { "code": null, "e": 29361, "s": 29347, "text": "Perl | Hashes" }, { "code": null, "e": 29379, "s": 29361, "text": "Perl | Data Types" } ]
Find single Movement in a Matrix - GeeksforGeeks
24 May, 2021 Given four integers x1, y1 and x2, y2 which represent two locations in an infinite 2D-Matrix, the task is to find whether it is possible to move from (x1, y1) to (x2, y2) in a single move, either left, right, up or down. Note that the move will be repeated until the destination is reached. If it is impossible to reach (x2, y2) output -1.Examples: Input: x1 = 0, y1 = 0, x2 = 1, y2 = 0 Output: Down Destination is just below the starting point.Input: x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output: -1 It is impossible to reach (1, 1) from (0, 0) in a single move. Approach: Check if the coordinates are either in the same row or in the same column then only its possible to reach the final destination. Then print the move according to the direction of the destination.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // Function that checks whether it is// possible to move from// (x1, y1) to (x2, y2)void Robot_Grid(int x1, int y1, int x2, int y2){ // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { cout << "Right"; } // Destination is // at the left else { cout << "Left"; } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { cout << "Down"; } // Destination is above // the current row else { cout << "Up"; } } // Impossible to get // to the destination else { cout << "-1"; }} // Driver codeint main(){ int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); return 0;} // Java implementation of the given above approach public class GFG{ // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) static void Robot_Grid(int x1, int y1, int x2, int y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { System.out.print("Right"); } // Destination is // at the left else { System.out.print("Left"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { System.out.print("Down"); } // Destination is above // the current row else { System.out.println("Up"); } } // Impossible to get // to the destination else { System.out.print("-1"); } } // Driver code public static void main(String []args) { int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2);} // This code is contributed by Ryuga} # Function that checks whether it is# possible to move from# (x1, y1) to (x2, y2) def Robot_Grid(x1, y1, x2, y2): # Both locations are in the same row if (x1 == x2): # Destination is at the right if (y1 < y2): print("Right") # Destination is at the left else: print("Left") # Both locations are in the same column elif (y1 == y2): # Destination is below the current row if (x1 < x2): print("Down") # Destination is above the current row else: print("Up") # Impossible to get to the destination else: print("-1") # Driver codeif __name__ == '__main__': x1 = 0 y1 = 0 x2 = 0 y2 = 1 Robot_Grid(x1, y1, x2, y2) # This code is contributed by# Sanjit_Prasad // C# implementation of the given above approachusing System; class GFG{ // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) static void Robot_Grid(int x1, int y1, int x2, int y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { Console.Write("Right"); } // Destination is // at the left else { Console.Write("Left"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { Console.Write("Down"); } // Destination is above // the current row else { Console.WriteLine("Up"); } } // Impossible to get // to the destination else { Console.WriteLine("-1"); } } // Driver code public static void Main() { int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); }} // This code is contributed by// Mukul Singh <?php// PHP implementation of the above approach // Function that checks whether it is// possible to move from// (x1, y1) to (x2, y2)function Robot_Grid($x1, $y1, $x2, $y2){ // Both locations are in the same row if ($x1 == $x2) { // Destination is at the right if ($y1 < $y2) { echo "Right"; } // Destination is at the left else { echo "Left"; } } // Both locations are in the same column else if ($y1 == $y2) { // Destination is below the // current row if ($x1 < $x2) { echo "Down"; } // Destination is above the current row else { echo "Up"; } } // Impossible to get to the destination else { echo "-1"; }} // Driver code$x1 = 0;$y1 = 0;$x2 = 0;$y2 = 1; Robot_Grid($x1, $y1, $x2, $y2); // This code is contributed by ita_c?> <script> // Javascript implementation of the given above approach // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) function Robot_Grid(x1,y1,x2,y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { document.write("Right"); } // Destination is // at the left else { document.write("Left"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { document.write("Down"); } // Destination is above // the current row else { document.write("Up"); } } // Impossible to get // to the destination else { document.write("-1"); } } // Driver code let x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); // This code is contributed by rag2127</script> Right ankthon Sanjit_Prasad Code_Mech ukasp rag2127 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26141, "s": 26113, "text": "\n24 May, 2021" }, { "code": null, "e": 26492, "s": 26141, "text": "Given four integers x1, y1 and x2, y2 which represent two locations in an infinite 2D-Matrix, the task is to find whether it is possible to move from (x1, y1) to (x2, y2) in a single move, either left, right, up or down. Note that the move will be repeated until the destination is reached. If it is impossible to reach (x2, y2) output -1.Examples: " }, { "code": null, "e": 26702, "s": 26492, "text": "Input: x1 = 0, y1 = 0, x2 = 1, y2 = 0 Output: Down Destination is just below the starting point.Input: x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output: -1 It is impossible to reach (1, 1) from (0, 0) in a single move. " }, { "code": null, "e": 26962, "s": 26704, "text": "Approach: Check if the coordinates are either in the same row or in the same column then only its possible to reach the final destination. Then print the move according to the direction of the destination.Below is the implementation of the above approach: " }, { "code": null, "e": 26966, "s": 26962, "text": "C++" }, { "code": null, "e": 26971, "s": 26966, "text": "Java" }, { "code": null, "e": 26979, "s": 26971, "text": "Python3" }, { "code": null, "e": 26982, "s": 26979, "text": "C#" }, { "code": null, "e": 26986, "s": 26982, "text": "PHP" }, { "code": null, "e": 26997, "s": 26986, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function that checks whether it is// possible to move from// (x1, y1) to (x2, y2)void Robot_Grid(int x1, int y1, int x2, int y2){ // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { cout << \"Right\"; } // Destination is // at the left else { cout << \"Left\"; } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { cout << \"Down\"; } // Destination is above // the current row else { cout << \"Up\"; } } // Impossible to get // to the destination else { cout << \"-1\"; }} // Driver codeint main(){ int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); return 0;}", "e": 27979, "s": 26997, "text": null }, { "code": "// Java implementation of the given above approach public class GFG{ // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) static void Robot_Grid(int x1, int y1, int x2, int y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { System.out.print(\"Right\"); } // Destination is // at the left else { System.out.print(\"Left\"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { System.out.print(\"Down\"); } // Destination is above // the current row else { System.out.println(\"Up\"); } } // Impossible to get // to the destination else { System.out.print(\"-1\"); } } // Driver code public static void main(String []args) { int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2);} // This code is contributed by Ryuga}", "e": 29318, "s": 27979, "text": null }, { "code": "# Function that checks whether it is# possible to move from# (x1, y1) to (x2, y2) def Robot_Grid(x1, y1, x2, y2): # Both locations are in the same row if (x1 == x2): # Destination is at the right if (y1 < y2): print(\"Right\") # Destination is at the left else: print(\"Left\") # Both locations are in the same column elif (y1 == y2): # Destination is below the current row if (x1 < x2): print(\"Down\") # Destination is above the current row else: print(\"Up\") # Impossible to get to the destination else: print(\"-1\") # Driver codeif __name__ == '__main__': x1 = 0 y1 = 0 x2 = 0 y2 = 1 Robot_Grid(x1, y1, x2, y2) # This code is contributed by# Sanjit_Prasad", "e": 30146, "s": 29318, "text": null }, { "code": "// C# implementation of the given above approachusing System; class GFG{ // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) static void Robot_Grid(int x1, int y1, int x2, int y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { Console.Write(\"Right\"); } // Destination is // at the left else { Console.Write(\"Left\"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { Console.Write(\"Down\"); } // Destination is above // the current row else { Console.WriteLine(\"Up\"); } } // Impossible to get // to the destination else { Console.WriteLine(\"-1\"); } } // Driver code public static void Main() { int x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); }} // This code is contributed by// Mukul Singh", "e": 31569, "s": 30146, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function that checks whether it is// possible to move from// (x1, y1) to (x2, y2)function Robot_Grid($x1, $y1, $x2, $y2){ // Both locations are in the same row if ($x1 == $x2) { // Destination is at the right if ($y1 < $y2) { echo \"Right\"; } // Destination is at the left else { echo \"Left\"; } } // Both locations are in the same column else if ($y1 == $y2) { // Destination is below the // current row if ($x1 < $x2) { echo \"Down\"; } // Destination is above the current row else { echo \"Up\"; } } // Impossible to get to the destination else { echo \"-1\"; }} // Driver code$x1 = 0;$y1 = 0;$x2 = 0;$y2 = 1; Robot_Grid($x1, $y1, $x2, $y2); // This code is contributed by ita_c?>", "e": 32517, "s": 31569, "text": null }, { "code": "<script> // Javascript implementation of the given above approach // Function that checks whether it is // possible to move from // (x1, y1) to (x2, y2) function Robot_Grid(x1,y1,x2,y2) { // Both locations are // in the same row if (x1 == x2) { // Destination is // at the right if (y1 < y2) { document.write(\"Right\"); } // Destination is // at the left else { document.write(\"Left\"); } } // Both locations are // in the same column else if (y1 == y2) { // Destination is below // the current row if (x1 < x2) { document.write(\"Down\"); } // Destination is above // the current row else { document.write(\"Up\"); } } // Impossible to get // to the destination else { document.write(\"-1\"); } } // Driver code let x1, x2, y1, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 1; Robot_Grid(x1, y1, x2, y2); // This code is contributed by rag2127</script>", "e": 33792, "s": 32517, "text": null }, { "code": null, "e": 33798, "s": 33792, "text": "Right" }, { "code": null, "e": 33808, "s": 33800, "text": "ankthon" }, { "code": null, "e": 33822, "s": 33808, "text": "Sanjit_Prasad" }, { "code": null, "e": 33832, "s": 33822, "text": "Code_Mech" }, { "code": null, "e": 33838, "s": 33832, "text": "ukasp" }, { "code": null, "e": 33846, "s": 33838, "text": "rag2127" }, { "code": null, "e": 33853, "s": 33846, "text": "Matrix" }, { "code": null, "e": 33872, "s": 33853, "text": "School Programming" }, { "code": null, "e": 33879, "s": 33872, "text": "Matrix" }, { "code": null, "e": 33977, "s": 33879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34027, "s": 33977, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 34084, "s": 34027, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 34121, "s": 34084, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 34162, "s": 34121, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 34226, "s": 34162, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 34244, "s": 34226, "text": "Python Dictionary" }, { "code": null, "e": 34260, "s": 34244, "text": "Arrays in C/C++" }, { "code": null, "e": 34279, "s": 34260, "text": "Inheritance in C++" }, { "code": null, "e": 34304, "s": 34279, "text": "Reverse a string in Java" } ]
Excel Cell References - GeeksforGeeks
20 May, 2021 A cell reference, also known as a cell address, is a mechanism that defines a cell on a worksheet by combining a column letter and a row number. We can refer to any cell (in Excel formulas) in the worksheet by using the cell references. For example : Here we refer to the cell in column A & row 2 by A2 & cell in column A & row 5 by A5. You can make use of such notations in any of the formula or to copy the value of one cell to other cell (by using = A2 or = A5). A cell reference is by default a relative reference, which means that the reference is relative to the cell’s position. If you refer to cell B1 from cell E1, for example, actually you would be referring to a cell that is 3 columns to the left (E-B = 3) within the same row number 1. When it is copied to other locations present in a worksheet, the relative reference for that location will be changed automatically. (because relative cell reference describes offset to another cell rather than a fixed address as In our example offset is : 3 columns left in the same row). Example 2: If you copy the formula = C2 / A2 from the cell “E2” to “E3”, the formula in E3 will automatically become =C3/A3. When copying or using AutoFill, there are times when the cell reference must stay the same. A column and/or row reference is kept constant using dollar signs. So, to get an absolute reference from a relative, we can use the dollar sign ($) characters. To refer to an actual fixed location on a worksheet whenever copying is done, we use absolute reference. The reference here is locked such that rows and columns do not shift when copied. Here Dollar ($) before row fixes the row & before the column fixes the column. Example: When we fix both row & column – Say if we want to lock row 2 & column A, we will use $A$2 as: G2 = C2/$A$2, when copied to G3, G3 becomes = C3/$A$2 Note: C3 is 4 columns left to G3 in the same row. Here original cell reference A2 is maintained whenever we copy G2 to any of the cells. So I3 = E3/$A$2 because E3 comes from the relative reference ( 4 columns left to the current one) & /$A$2 comes from the absolute reference. Therefore, I3 = E3//$A$2 = 12/10 = 1.2 We can use relative and absolute cell references to calculate dates. Example : To Calculate the Date of Delivery online from the given date of the order placed & no of days it will take to deliver : Here, We calculate the Date of Delivery by = Order Date + No of days to deliver. We used Relative cell reference so that individual product delivery dates can be calculated. Absolute cell references for calculating dates : Example: To Calculate the Date of Birth When the age is known is a number of days using Current date can be done by making use of absolute reference. Here, We calculate DOB by = Current Date – Age in days. The Current date is contained in the cell E2 & in subtraction, we fixed that date to subtract the days from. An absolute column and relative row, or an absolute row and relative column, is a mixed cell reference. You get an absolute column or absolute row when you individually put the $ before the column letter or before the row number. Example : $B8 is relative for row 8 but absolute for column B; and B$8 is absolute for row 1 but relative for column A. Here Dollar ($) before row number fixes/locks the row & before the column name fixes/locks the column. Example: When we fix the only row: If we have G2 = C2/A$2 then : We used $ before the row number, so we are locking the only row here. When G2 is copied to G3, G3 = C3/A$2 (not C3/A3) because the row has been fixed already. Here, whenever we copy G2 to any other cell, always the divisor will refer to a fixed row 2 (column vary according to the concept of relative reference) So, when G2 is copied to I3, I3 = E3/C$2 because E3 comes from the relative reference (4 columns left to the current one) & C$2 comes from the absolute reference for row & relative reference for Column ( 6 Columns left to the current one) You will want to refer to all the cells inside a particular column when operating with an Excel worksheet with any number of rows. Simply type a column letter twice with a colon in between to refer to the entire column B, for example, B:B. Example: You may want to find the sum of a column of data in certain cases. While you can do this with a regular cell range, such as =SUM(B1:B10), you will need to change the cell range if your spreadsheet grows in size. Excel, on the other hand, has a cell range that do not require the row number and takes all the cells in the column in action. If you wanted to find the sum of all the values in column B, for example, you would type =SUM (B:B). You can add as much data as you want to your spreadsheet without having to change your cell ranges if you use this type of cell range. You will want to refer to all the cells inside a particular row when operating with an Excel worksheet with any number of columns. Simply type a row number twice with a colon in between to refer to the entire row, for example, 2:2. Example: You may want to find the sum of a row of data in certain cases. While you can do this with a regular cell range, such as =SUM(A2 : J2), you will need to change the cell range if your spreadsheet grows in size. Excel, on the other hand, has a cell range that do not require the column letter and takes all the cells in the row in action. If you wanted to find the sum of all the values in row 2, for example, you would type =SUM (2:2). You can add as much data as you want to your spreadsheet without having to change your cell ranges if you use this type of cell range. To refer to the entire column excluding the first few rows, you need to specify the range as we give in a normal fashion. We know that the Excel worksheets can have only 1,048,576 rows. (To check this go to an empty cell & press: Ctrl + Down arrow Key) So, we can do the sum of the entire column B except for the first 5 rows by = SUM(B6:B1048576). You can also create a mixed entire-column reference, say for example $B:B. But, practically it is difficult to find a situation where it would be used. Example : The $ sign can be manually typed in an Excel formula to adjust a relative cell relation to absolute or mixed. You can also speed things up by pressing the F4 key. You must be in formula edit mode to use the F4 shortcut. The steps are :Firstly, Choose the cell that contains the formula. Then by pressing the F2 key or double-clicking the cell, you can enter Edit mode. Select the cell reference in which you want to make changes. Then, switch between four-cell reference forms by pressing F4. Example: When you select a cell having only relative reference (i.e., no $ sign), say = B2: The first time when you press F4, it becomes =$B$2 The second time when you press F4, it becomes =B$2 The third time when you press F4, it becomes=$B2 The fourth time when you press F4, it becomes back to the relative reference=B2 B2 --Press F4--> =$B$2 --Press F4--> =B$2 --Press F4--> = =$B2 --Press F4--> =B2 So, using F4, you do not require to manually type the $ symbol. 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 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 Calculate Deciles in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n20 May, 2021" }, { "code": null, "e": 26526, "s": 26289, "text": "A cell reference, also known as a cell address, is a mechanism that defines a cell on a worksheet by combining a column letter and a row number. We can refer to any cell (in Excel formulas) in the worksheet by using the cell references." }, { "code": null, "e": 26540, "s": 26526, "text": "For example :" }, { "code": null, "e": 26755, "s": 26540, "text": "Here we refer to the cell in column A & row 2 by A2 & cell in column A & row 5 by A5. You can make use of such notations in any of the formula or to copy the value of one cell to other cell (by using = A2 or = A5)." }, { "code": null, "e": 27040, "s": 26755, "text": "A cell reference is by default a relative reference, which means that the reference is relative to the cell’s position. If you refer to cell B1 from cell E1, for example, actually you would be referring to a cell that is 3 columns to the left (E-B = 3) within the same row number 1. " }, { "code": null, "e": 27330, "s": 27040, "text": "When it is copied to other locations present in a worksheet, the relative reference for that location will be changed automatically. (because relative cell reference describes offset to another cell rather than a fixed address as In our example offset is : 3 columns left in the same row)." }, { "code": null, "e": 27456, "s": 27330, "text": "Example 2: If you copy the formula = C2 / A2 from the cell “E2” to “E3”, the formula in E3 will automatically become =C3/A3." }, { "code": null, "e": 27708, "s": 27456, "text": "When copying or using AutoFill, there are times when the cell reference must stay the same. A column and/or row reference is kept constant using dollar signs. So, to get an absolute reference from a relative, we can use the dollar sign ($) characters." }, { "code": null, "e": 27896, "s": 27708, "text": "To refer to an actual fixed location on a worksheet whenever copying is done, we use absolute reference. The reference here is locked such that rows and columns do not shift when copied. " }, { "code": null, "e": 27975, "s": 27896, "text": "Here Dollar ($) before row fixes the row & before the column fixes the column." }, { "code": null, "e": 28079, "s": 27975, "text": "Example: When we fix both row & column – Say if we want to lock row 2 & column A, we will use $A$2 as:" }, { "code": null, "e": 28133, "s": 28079, "text": "G2 = C2/$A$2, when copied to G3, G3 becomes = C3/$A$2" }, { "code": null, "e": 28184, "s": 28133, "text": " Note: C3 is 4 columns left to G3 in the same row." }, { "code": null, "e": 28413, "s": 28184, "text": "Here original cell reference A2 is maintained whenever we copy G2 to any of the cells. So I3 = E3/$A$2 because E3 comes from the relative reference ( 4 columns left to the current one) & /$A$2 comes from the absolute reference." }, { "code": null, "e": 28453, "s": 28413, "text": "Therefore, I3 = E3//$A$2 = 12/10 = 1.2" }, { "code": null, "e": 28522, "s": 28453, "text": "We can use relative and absolute cell references to calculate dates." }, { "code": null, "e": 28652, "s": 28522, "text": "Example : To Calculate the Date of Delivery online from the given date of the order placed & no of days it will take to deliver :" }, { "code": null, "e": 28826, "s": 28652, "text": "Here, We calculate the Date of Delivery by = Order Date + No of days to deliver. We used Relative cell reference so that individual product delivery dates can be calculated." }, { "code": null, "e": 28875, "s": 28826, "text": "Absolute cell references for calculating dates :" }, { "code": null, "e": 29026, "s": 28875, "text": "Example: To Calculate the Date of Birth When the age is known is a number of days using Current date can be done by making use of absolute reference. " }, { "code": null, "e": 29191, "s": 29026, "text": "Here, We calculate DOB by = Current Date – Age in days. The Current date is contained in the cell E2 & in subtraction, we fixed that date to subtract the days from." }, { "code": null, "e": 29541, "s": 29191, "text": "An absolute column and relative row, or an absolute row and relative column, is a mixed cell reference. You get an absolute column or absolute row when you individually put the $ before the column letter or before the row number. Example : $B8 is relative for row 8 but absolute for column B; and B$8 is absolute for row 1 but relative for column A." }, { "code": null, "e": 29644, "s": 29541, "text": "Here Dollar ($) before row number fixes/locks the row & before the column name fixes/locks the column." }, { "code": null, "e": 29709, "s": 29644, "text": "Example: When we fix the only row: If we have G2 = C2/A$2 then :" }, { "code": null, "e": 29869, "s": 29709, "text": "We used $ before the row number, so we are locking the only row here. When G2 is copied to G3, G3 = C3/A$2 (not C3/A3) because the row has been fixed already." }, { "code": null, "e": 30022, "s": 29869, "text": "Here, whenever we copy G2 to any other cell, always the divisor will refer to a fixed row 2 (column vary according to the concept of relative reference)" }, { "code": null, "e": 30263, "s": 30022, "text": "So, when G2 is copied to I3, I3 = E3/C$2 because E3 comes from the relative reference (4 columns left to the current one) & C$2 comes from the absolute reference for row & relative reference for Column ( 6 Columns left to the current one)" }, { "code": null, "e": 30503, "s": 30263, "text": "You will want to refer to all the cells inside a particular column when operating with an Excel worksheet with any number of rows. Simply type a column letter twice with a colon in between to refer to the entire column B, for example, B:B." }, { "code": null, "e": 30724, "s": 30503, "text": "Example: You may want to find the sum of a column of data in certain cases. While you can do this with a regular cell range, such as =SUM(B1:B10), you will need to change the cell range if your spreadsheet grows in size." }, { "code": null, "e": 31087, "s": 30724, "text": "Excel, on the other hand, has a cell range that do not require the row number and takes all the cells in the column in action. If you wanted to find the sum of all the values in column B, for example, you would type =SUM (B:B). You can add as much data as you want to your spreadsheet without having to change your cell ranges if you use this type of cell range." }, { "code": null, "e": 31319, "s": 31087, "text": "You will want to refer to all the cells inside a particular row when operating with an Excel worksheet with any number of columns. Simply type a row number twice with a colon in between to refer to the entire row, for example, 2:2." }, { "code": null, "e": 31538, "s": 31319, "text": "Example: You may want to find the sum of a row of data in certain cases. While you can do this with a regular cell range, such as =SUM(A2 : J2), you will need to change the cell range if your spreadsheet grows in size." }, { "code": null, "e": 31898, "s": 31538, "text": "Excel, on the other hand, has a cell range that do not require the column letter and takes all the cells in the row in action. If you wanted to find the sum of all the values in row 2, for example, you would type =SUM (2:2). You can add as much data as you want to your spreadsheet without having to change your cell ranges if you use this type of cell range." }, { "code": null, "e": 32151, "s": 31898, "text": "To refer to the entire column excluding the first few rows, you need to specify the range as we give in a normal fashion. We know that the Excel worksheets can have only 1,048,576 rows. (To check this go to an empty cell & press: Ctrl + Down arrow Key)" }, { "code": null, "e": 32247, "s": 32151, "text": "So, we can do the sum of the entire column B except for the first 5 rows by = SUM(B6:B1048576)." }, { "code": null, "e": 32399, "s": 32247, "text": "You can also create a mixed entire-column reference, say for example $B:B. But, practically it is difficult to find a situation where it would be used." }, { "code": null, "e": 32409, "s": 32399, "text": "Example :" }, { "code": null, "e": 32902, "s": 32409, "text": "The $ sign can be manually typed in an Excel formula to adjust a relative cell relation to absolute or mixed. You can also speed things up by pressing the F4 key. You must be in formula edit mode to use the F4 shortcut. The steps are :Firstly, Choose the cell that contains the formula. Then by pressing the F2 key or double-clicking the cell, you can enter Edit mode. Select the cell reference in which you want to make changes. Then, switch between four-cell reference forms by pressing F4." }, { "code": null, "e": 32994, "s": 32902, "text": "Example: When you select a cell having only relative reference (i.e., no $ sign), say = B2:" }, { "code": null, "e": 33045, "s": 32994, "text": "The first time when you press F4, it becomes =$B$2" }, { "code": null, "e": 33096, "s": 33045, "text": "The second time when you press F4, it becomes =B$2" }, { "code": null, "e": 33145, "s": 33096, "text": "The third time when you press F4, it becomes=$B2" }, { "code": null, "e": 33225, "s": 33145, "text": "The fourth time when you press F4, it becomes back to the relative reference=B2" }, { "code": null, "e": 33308, "s": 33225, "text": "B2 --Press F4--> =$B$2 --Press F4--> =B$2 --Press F4--> = =$B2 --Press F4--> =B2" }, { "code": null, "e": 33372, "s": 33308, "text": "So, using F4, you do not require to manually type the $ symbol." }, { "code": null, "e": 33379, "s": 33372, "text": "Picked" }, { "code": null, "e": 33385, "s": 33379, "text": "Excel" }, { "code": null, "e": 33483, "s": 33385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33511, "s": 33483, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 33566, "s": 33511, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 33607, "s": 33566, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 33657, "s": 33607, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 33673, "s": 33657, "text": "Macros in Excel" }, { "code": null, "e": 33731, "s": 33673, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 33782, "s": 33731, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 33838, "s": 33782, "text": "How to Remove Duplicates From Array Using VBA in Excel?" }, { "code": null, "e": 33873, "s": 33838, "text": "How to Calculate Deciles in Excel?" } ]
How to convert JSON string to array of JSON objects using JavaScript ? - GeeksforGeeks
30 Jul, 2021 Given a JSON string and the task is to convert the JSON string to the array of JSON objects. This array contains the values of JavaScript object obtained from the JSON string with the help of JavaScript. There are two approaches to solve this problem which are discussed below: Approach 1: First convert the JSON string to the JavaScript object using JSON.Parse() method and then take out the values of the object and push them into the array using push() method. Example:<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = JSON.parse(JS_Obj); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = JSON.parse(JS_Obj); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } </script> </body> </html> Output: Approach 2: This approach is also the same but using a different method. Convert the JSON string to the JavaScript object using eval() method and then take out the values of the object and push them to the array using push() method. Example:<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <button onclick = "myGFG()"> Click Here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } </script> </body> </html> Output: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. 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. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc HTML-Misc JavaScript-Misc 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 apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26747, "s": 26719, "text": "\n30 Jul, 2021" }, { "code": null, "e": 27025, "s": 26747, "text": "Given a JSON string and the task is to convert the JSON string to the array of JSON objects. This array contains the values of JavaScript object obtained from the JSON string with the help of JavaScript. There are two approaches to solve this problem which are discussed below:" }, { "code": null, "e": 27211, "s": 27025, "text": "Approach 1: First convert the JSON string to the JavaScript object using JSON.Parse() method and then take out the values of the object and push them into the array using push() method." }, { "code": null, "e": 28229, "s": 27211, "text": "Example:<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <button onclick = \"myGFG()\"> Click Here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById(\"GFG_UP\"); var JS_Obj = '{\"prop_1\":\"val_1\", \"prop_2\":\"val_2\", \"prop_3\" : \"val_3\"}'; up.innerHTML = \"JSON string - '\" + JS_Obj + \"'\"; var down = document.getElementById(\"GFG_DOWN\"); function myGFG() { var obj = JSON.parse(JS_Obj); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = \"Array of values - [\" + res + \"]\"; } </script> </body> </html>" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <button onclick = \"myGFG()\"> Click Here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById(\"GFG_UP\"); var JS_Obj = '{\"prop_1\":\"val_1\", \"prop_2\":\"val_2\", \"prop_3\" : \"val_3\"}'; up.innerHTML = \"JSON string - '\" + JS_Obj + \"'\"; var down = document.getElementById(\"GFG_DOWN\"); function myGFG() { var obj = JSON.parse(JS_Obj); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = \"Array of values - [\" + res + \"]\"; } </script> </body> </html>", "e": 29239, "s": 28229, "text": null }, { "code": null, "e": 29247, "s": 29239, "text": "Output:" }, { "code": null, "e": 29480, "s": 29247, "text": "Approach 2: This approach is also the same but using a different method. Convert the JSON string to the JavaScript object using eval() method and then take out the values of the object and push them to the array using push() method." }, { "code": null, "e": 30504, "s": 29480, "text": "Example:<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <button onclick = \"myGFG()\"> Click Here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById(\"GFG_UP\"); var JS_Obj = '{\"prop_1\":\"val_1\", \"prop_2\":\"val_2\", \"prop_3\" : \"val_3\"}'; up.innerHTML = \"JSON string - '\" + JS_Obj + \"'\"; var down = document.getElementById(\"GFG_DOWN\"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = \"Array of values - [\" + res + \"]\"; } </script> </body> </html>" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON string to array of JSON objects using JavaScript? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <button onclick = \"myGFG()\"> Click Here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById(\"GFG_UP\"); var JS_Obj = '{\"prop_1\":\"val_1\", \"prop_2\":\"val_2\", \"prop_3\" : \"val_3\"}'; up.innerHTML = \"JSON string - '\" + JS_Obj + \"'\"; var down = document.getElementById(\"GFG_DOWN\"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = \"Array of values - [\" + res + \"]\"; } </script> </body> </html>", "e": 31520, "s": 30504, "text": null }, { "code": null, "e": 31528, "s": 31520, "text": "Output:" }, { "code": null, "e": 31747, "s": 31528, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 31941, "s": 31747, "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": 32127, "s": 31941, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 32136, "s": 32127, "text": "CSS-Misc" }, { "code": null, "e": 32146, "s": 32136, "text": "HTML-Misc" }, { "code": null, "e": 32162, "s": 32146, "text": "JavaScript-Misc" }, { "code": null, "e": 32166, "s": 32162, "text": "CSS" }, { "code": null, "e": 32171, "s": 32166, "text": "HTML" }, { "code": null, "e": 32182, "s": 32171, "text": "JavaScript" }, { "code": null, "e": 32199, "s": 32182, "text": "Web Technologies" }, { "code": null, "e": 32226, "s": 32199, "text": "Web technologies Questions" }, { "code": null, "e": 32231, "s": 32226, "text": "HTML" }, { "code": null, "e": 32329, "s": 32231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32384, "s": 32329, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32423, "s": 32384, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32460, "s": 32423, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32501, "s": 32460, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 32530, "s": 32501, "text": "Form validation using jQuery" }, { "code": null, "e": 32590, "s": 32530, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32643, "s": 32590, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32704, "s": 32643, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32728, "s": 32704, "text": "REST API (Introduction)" } ]
NumberFormat getNumberInstance() method in Java with Examples - GeeksforGeeks
01 Apr, 2019 The getNumberInstance() method is a built-in method of the java.text.NumberFormat returns an general purpose number format for the current default FORMAT locale.Syntax:public static final NumberFormat getNumberInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance()The getNumberInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a general-purpose number format for any specified locale.Syntax:public static NumberFormat getNumberInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for general purpose number formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale) The getNumberInstance() method is a built-in method of the java.text.NumberFormat returns an general purpose number format for the current default FORMAT locale.Syntax:public static final NumberFormat getNumberInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance() Syntax: public static final NumberFormat getNumberInstance() Parameters: The function does not accepts any parameter. Return Value: The function returns the NumberFormat instance for general purpose formatting. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Program 2: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} US Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance() The getNumberInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a general-purpose number format for any specified locale.Syntax:public static NumberFormat getNumberInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for general purpose number formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale) Syntax: public static NumberFormat getNumberInstance(Locale inLocale) Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified. Return Value: The function returns the NumberFormat instance for general purpose number formatting. Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale) Java-Functions Java-NumberFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25797, "s": 25769, "text": "\n01 Apr, 2019" }, { "code": null, "e": 28768, "s": 25797, "text": "The getNumberInstance() method is a built-in method of the java.text.NumberFormat returns an general purpose number format for the current default FORMAT locale.Syntax:public static final NumberFormat getNumberInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance()The getNumberInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a general-purpose number format for any specified locale.Syntax:public static NumberFormat getNumberInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for general purpose number formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale)" }, { "code": null, "e": 30541, "s": 28768, "text": "The getNumberInstance() method is a built-in method of the java.text.NumberFormat returns an general purpose number format for the current default FORMAT locale.Syntax:public static final NumberFormat getNumberInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for general purpose formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance()" }, { "code": null, "e": 30549, "s": 30541, "text": "Syntax:" }, { "code": null, "e": 30602, "s": 30549, "text": "public static final NumberFormat getNumberInstance()" }, { "code": null, "e": 30659, "s": 30602, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 30752, "s": 30659, "text": "Return Value: The function returns the NumberFormat instance for general purpose formatting." }, { "code": null, "e": 30803, "s": 30752, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 30814, "s": 30803, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency().getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 31471, "s": 30814, "text": null }, { "code": null, "e": 31488, "s": 31471, "text": "Canadian Dollar\n" }, { "code": null, "e": 31499, "s": 31488, "text": "Program 2:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the number instance NumberFormat nF = NumberFormat .getNumberInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 32037, "s": 31499, "text": null }, { "code": null, "e": 32048, "s": 32037, "text": "US Dollar\n" }, { "code": null, "e": 32150, "s": 32048, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance()" }, { "code": null, "e": 33349, "s": 32150, "text": "The getNumberInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a general-purpose number format for any specified locale.Syntax:public static NumberFormat getNumberInstance(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified.Return Value: The function returns the NumberFormat instance for general purpose number formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale)" }, { "code": null, "e": 33357, "s": 33349, "text": "Syntax:" }, { "code": null, "e": 33419, "s": 33357, "text": "public static NumberFormat getNumberInstance(Locale inLocale)" }, { "code": null, "e": 33540, "s": 33419, "text": "Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specified." }, { "code": null, "e": 33640, "s": 33540, "text": "Return Value: The function returns the NumberFormat instance for general purpose number formatting." }, { "code": null, "e": 33691, "s": 33640, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 33702, "s": 33691, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the integer instance NumberFormat nF = NumberFormat.getNumberInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 34252, "s": 33702, "text": null }, { "code": null, "e": 34269, "s": 34252, "text": "Canadian Dollar\n" }, { "code": null, "e": 34387, "s": 34269, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getNumberInstance(java.util.Locale)" }, { "code": null, "e": 34402, "s": 34387, "text": "Java-Functions" }, { "code": null, "e": 34420, "s": 34402, "text": "Java-NumberFormat" }, { "code": null, "e": 34438, "s": 34420, "text": "Java-text package" }, { "code": null, "e": 34443, "s": 34438, "text": "Java" }, { "code": null, "e": 34448, "s": 34443, "text": "Java" }, { "code": null, "e": 34546, "s": 34448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34597, "s": 34546, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34627, "s": 34597, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34646, "s": 34627, "text": "Interfaces in Java" }, { "code": null, "e": 34661, "s": 34646, "text": "Stream In Java" }, { "code": null, "e": 34692, "s": 34661, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34710, "s": 34692, "text": "ArrayList in Java" }, { "code": null, "e": 34742, "s": 34710, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34762, "s": 34742, "text": "Stack Class in Java" }, { "code": null, "e": 34794, "s": 34762, "text": "Multidimensional Arrays in Java" } ]
Longest set of Palindrome Numbers from the range [L, R] with at most K difference between its maximum and minimum - GeeksforGeeks
26 Jul, 2021 Given three positive integers L, R, and K, the task is to find the largest group of palindromic numbers from the range [L, R] such that the difference between the maximum and the minimum element present in the group is less than K. Examples: Input: L = 50, R = 78, K = 12Output: 2Explanation:All palindromic numbers from the range [50, 78] are {55, 66, 77}.The group of palindromic numbers {55, 66} have the difference between the maximum and minimum element as 11, which is less than K( = 12).Therefore, the size of the group is 2. Input: L = 98, R = 112, K = 13Output: 3 Approach: The given problem can be solved by using Binary Search. Follow the steps below to solve the problem: Initialize an auxiliary array, say arr[], and store all the palindrome numbers present in the range [L, R]. Define a function, say search(arr, X), to find the rightmost index with value less than X:Initialize three variables, say low as 0, high as (arr.size() – 1), and ans as -1.Iterate until low ≤ high and perform the following operations:Calculate mid as low+ (high – low)/2.If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1).Otherwise, update the value of high as (mid – 1).After completing the above steps, return the value of ans as the result. Initialize three variables, say low as 0, high as (arr.size() – 1), and ans as -1. Iterate until low ≤ high and perform the following operations:Calculate mid as low+ (high – low)/2.If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1).Otherwise, update the value of high as (mid – 1). Calculate mid as low+ (high – low)/2. If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1). Otherwise, update the value of high as (mid – 1). After completing the above steps, return the value of ans as the result. Traverse the array arr[] and perform the following steps:Find the rightmost index, which is less than or equal to (arr[i] + K – 1) using function search() and store it in a variable, say rightIndex.If the value of rightIndex is not equal to -1, then update the value of count as the maximum of count and (rightIndex – i + 1). Find the rightmost index, which is less than or equal to (arr[i] + K – 1) using function search() and store it in a variable, say rightIndex. If the value of rightIndex is not equal to -1, then update the value of count as the maximum of count and (rightIndex – i + 1). After completing the above steps, print the value of count as the resultant. 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 search the// rightmost index of given numberstatic int search(vector<int> list, int num){ int low = 0, high = list.size() - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notbool isPalindrome(int n){ int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp;} // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kint countNumbers(int L, int R, int K){ // Stores the all the palindromic // numbers in the range [L, R] vector<int> list; // Traverse over the range [L, R] for(int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.push_back(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for(int i = 0; i < list.size(); i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = max(count, right_index - i + 1); } // Return the count return count;} // Driver Codeint main(){ int L = 98, R = 112; int K = 13; cout << countNumbers(L, R, K);} // This code is contributed by ipg2016107 // Java program for the above approachimport java.util.*; public class Main { // Function to find the maximum size // of group of palindrome numbers // having difference between maximum // and minimum element at most K static int countNumbers(int L, int R, int K) { // Stores the all the palindromic // numbers in the range [L, R] ArrayList<Integer> list = new ArrayList<>(); // Traverse over the range [L, R] for (int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.add(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for (int i = 0; i < list.size(); i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list.get(i) + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.max(count, right_index - i + 1); } // Return the count return count; } // Function to search the // rightmost index of given number static int search( ArrayList<Integer> list, int num) { int low = 0, high = list.size() - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list.get(mid) <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans; } // Function to check if the given // number is palindrome or not static boolean isPalindrome(int n) { int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp; } // Driver Code public static void main(String args[]) { int L = 98, R = 112; int K = 13; System.out.print( countNumbers(L, R, K)); }} # Python3 program for the above approach # Function to find the maximum size# of group of palindrome numbers# having difference between maximum# and minimum element at most Kdef countNumbers(L, R, K): # Stores the all the palindromic # numbers in the range [L, R] list = [] # Traverse over the range [L, R] for i in range(L, R + 1): # If i is a palindrome if (isPalindrome(i)): # Append the number # in the list list.append(i) # Stores count of maximum # palindromic numbers count = 0 # Iterate each element in the list for i in range(len(list)): # Calculate rightmost index in # the list < current element + K right_index = search(list, list[i] + K - 1) # Check if there is rightmost # index from the current index if (right_index != -1): count = max(count, right_index - i + 1) # Return the count return count # Function to search the# rightmost index of given numberdef search(list, num): low, high = 0, len(list) - 1 # Store the rightmost index ans = -1 while (low <= high): # Calculate the mid mid = low + (high - low) // 2 # If given number <= num if (list[mid] <= num): # Assign ans = mid ans = mid # Update low low = mid + 1 else: # Update high high = mid - 1 # return ans return ans # Function to check if the given# number is palindrome or notdef isPalindrome(n): rev = 0 temp = n # Generate reverse # of the given number while (n > 0): rev = rev * 10 + n % 10 n //= 10 # If n is a palindrome return rev == temp # Driver Codeif __name__ == '__main__': L, R = 98, 112 K = 13 print(countNumbers(L, R, K)) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kstatic int countNumbers(int L, int R, int K){ // Stores the all the palindromic // numbers in the range [L, R] List<int> list = new List<int>(); // Traverse over the range [L, R] for(int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.Add(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for(int i = 0; i < list.Count; i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.Max(count, right_index - i + 1); } // Return the count return count;} // Function to search the// rightmost index of given numberstatic int search(List<int> list, int num){ int low = 0, high = list.Count - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notstatic bool isPalindrome(int n){ int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp;} // Driver Codepublic static void Main(string[] args){ int L = 98, R = 112; int K = 13; Console.WriteLine(countNumbers(L, R, K));}} // This code is contributed by avijitmondal1998 <script> // Javascript program for the above approach // Function to search the// rightmost index of given numberfunction search(list, num){ var low = 0, high = list.length - 1; // Store the rightmost index var ans = -1; while (low <= high) { // Calculate the mid var mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notfunction isPalindrome(n){ var rev = 0; var temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n = parseInt(n/10); } // If n is a palindrome return rev == temp;} // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kfunction countNumbers(L, R, K){ // Stores the all the palindromic // numbers in the range [L, R] var list = []; // Traverse over the range [L, R] for(var i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.push(i); } } // Stores count of maximum // palindromic numbers var count = 0; // Iterate each element in the list for(var i = 0; i < list.length; i++) { // Calculate rightmost index in // the list < current element + K var right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.max(count, right_index - i + 1); } // Return the count return count;} // Driver Codevar L = 98, R = 112;var K = 13;document.write( countNumbers(L, R, K)); // This code is contributed by noob2000.</script> 3 Time Complexity: O((R – L) * log(R – L))Auxiliary Space: O(R – L) mohit kumar 29 avijitmondal1998 ipg2016107 noob2000 sooda367 sweetyty adnanirshad158 palindrome Reverse Mathematical Searching Searching Mathematical palindrome Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 25937, "s": 25909, "text": "\n26 Jul, 2021" }, { "code": null, "e": 26169, "s": 25937, "text": "Given three positive integers L, R, and K, the task is to find the largest group of palindromic numbers from the range [L, R] such that the difference between the maximum and the minimum element present in the group is less than K." }, { "code": null, "e": 26179, "s": 26169, "text": "Examples:" }, { "code": null, "e": 26471, "s": 26179, "text": "Input: L = 50, R = 78, K = 12Output: 2Explanation:All palindromic numbers from the range [50, 78] are {55, 66, 77}.The group of palindromic numbers {55, 66} have the difference between the maximum and minimum element as 11, which is less than K( = 12).Therefore, the size of the group is 2. " }, { "code": null, "e": 26511, "s": 26471, "text": "Input: L = 98, R = 112, K = 13Output: 3" }, { "code": null, "e": 26622, "s": 26511, "text": "Approach: The given problem can be solved by using Binary Search. Follow the steps below to solve the problem:" }, { "code": null, "e": 26730, "s": 26622, "text": "Initialize an auxiliary array, say arr[], and store all the palindrome numbers present in the range [L, R]." }, { "code": null, "e": 27220, "s": 26730, "text": "Define a function, say search(arr, X), to find the rightmost index with value less than X:Initialize three variables, say low as 0, high as (arr.size() – 1), and ans as -1.Iterate until low ≤ high and perform the following operations:Calculate mid as low+ (high – low)/2.If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1).Otherwise, update the value of high as (mid – 1).After completing the above steps, return the value of ans as the result." }, { "code": null, "e": 27303, "s": 27220, "text": "Initialize three variables, say low as 0, high as (arr.size() – 1), and ans as -1." }, { "code": null, "e": 27549, "s": 27303, "text": "Iterate until low ≤ high and perform the following operations:Calculate mid as low+ (high – low)/2.If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1).Otherwise, update the value of high as (mid – 1)." }, { "code": null, "e": 27587, "s": 27549, "text": "Calculate mid as low+ (high – low)/2." }, { "code": null, "e": 27685, "s": 27587, "text": "If the value at index mid is at most X, then update the value of ans as mid and low as (mid + 1)." }, { "code": null, "e": 27735, "s": 27685, "text": "Otherwise, update the value of high as (mid – 1)." }, { "code": null, "e": 27808, "s": 27735, "text": "After completing the above steps, return the value of ans as the result." }, { "code": null, "e": 28135, "s": 27808, "text": "Traverse the array arr[] and perform the following steps:Find the rightmost index, which is less than or equal to (arr[i] + K – 1) using function search() and store it in a variable, say rightIndex.If the value of rightIndex is not equal to -1, then update the value of count as the maximum of count and (rightIndex – i + 1)." }, { "code": null, "e": 28277, "s": 28135, "text": "Find the rightmost index, which is less than or equal to (arr[i] + K – 1) using function search() and store it in a variable, say rightIndex." }, { "code": null, "e": 28406, "s": 28277, "text": "If the value of rightIndex is not equal to -1, then update the value of count as the maximum of count and (rightIndex – i + 1)." }, { "code": null, "e": 28483, "s": 28406, "text": "After completing the above steps, print the value of count as the resultant." }, { "code": null, "e": 28534, "s": 28483, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28538, "s": 28534, "text": "C++" }, { "code": null, "e": 28543, "s": 28538, "text": "Java" }, { "code": null, "e": 28551, "s": 28543, "text": "Python3" }, { "code": null, "e": 28554, "s": 28551, "text": "C#" }, { "code": null, "e": 28565, "s": 28554, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to search the// rightmost index of given numberstatic int search(vector<int> list, int num){ int low = 0, high = list.size() - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notbool isPalindrome(int n){ int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp;} // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kint countNumbers(int L, int R, int K){ // Stores the all the palindromic // numbers in the range [L, R] vector<int> list; // Traverse over the range [L, R] for(int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.push_back(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for(int i = 0; i < list.size(); i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = max(count, right_index - i + 1); } // Return the count return count;} // Driver Codeint main(){ int L = 98, R = 112; int K = 13; cout << countNumbers(L, R, K);} // This code is contributed by ipg2016107", "e": 30780, "s": 28565, "text": null }, { "code": "// Java program for the above approachimport java.util.*; public class Main { // Function to find the maximum size // of group of palindrome numbers // having difference between maximum // and minimum element at most K static int countNumbers(int L, int R, int K) { // Stores the all the palindromic // numbers in the range [L, R] ArrayList<Integer> list = new ArrayList<>(); // Traverse over the range [L, R] for (int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.add(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for (int i = 0; i < list.size(); i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list.get(i) + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.max(count, right_index - i + 1); } // Return the count return count; } // Function to search the // rightmost index of given number static int search( ArrayList<Integer> list, int num) { int low = 0, high = list.size() - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list.get(mid) <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans; } // Function to check if the given // number is palindrome or not static boolean isPalindrome(int n) { int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp; } // Driver Code public static void main(String args[]) { int L = 98, R = 112; int K = 13; System.out.print( countNumbers(L, R, K)); }}", "e": 33333, "s": 30780, "text": null }, { "code": "# Python3 program for the above approach # Function to find the maximum size# of group of palindrome numbers# having difference between maximum# and minimum element at most Kdef countNumbers(L, R, K): # Stores the all the palindromic # numbers in the range [L, R] list = [] # Traverse over the range [L, R] for i in range(L, R + 1): # If i is a palindrome if (isPalindrome(i)): # Append the number # in the list list.append(i) # Stores count of maximum # palindromic numbers count = 0 # Iterate each element in the list for i in range(len(list)): # Calculate rightmost index in # the list < current element + K right_index = search(list, list[i] + K - 1) # Check if there is rightmost # index from the current index if (right_index != -1): count = max(count, right_index - i + 1) # Return the count return count # Function to search the# rightmost index of given numberdef search(list, num): low, high = 0, len(list) - 1 # Store the rightmost index ans = -1 while (low <= high): # Calculate the mid mid = low + (high - low) // 2 # If given number <= num if (list[mid] <= num): # Assign ans = mid ans = mid # Update low low = mid + 1 else: # Update high high = mid - 1 # return ans return ans # Function to check if the given# number is palindrome or notdef isPalindrome(n): rev = 0 temp = n # Generate reverse # of the given number while (n > 0): rev = rev * 10 + n % 10 n //= 10 # If n is a palindrome return rev == temp # Driver Codeif __name__ == '__main__': L, R = 98, 112 K = 13 print(countNumbers(L, R, K)) # This code is contributed by mohit kumar 29.", "e": 35234, "s": 33333, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kstatic int countNumbers(int L, int R, int K){ // Stores the all the palindromic // numbers in the range [L, R] List<int> list = new List<int>(); // Traverse over the range [L, R] for(int i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.Add(i); } } // Stores count of maximum // palindromic numbers int count = 0; // Iterate each element in the list for(int i = 0; i < list.Count; i++) { // Calculate rightmost index in // the list < current element + K int right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.Max(count, right_index - i + 1); } // Return the count return count;} // Function to search the// rightmost index of given numberstatic int search(List<int> list, int num){ int low = 0, high = list.Count - 1; // Store the rightmost index int ans = -1; while (low <= high) { // Calculate the mid int mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notstatic bool isPalindrome(int n){ int rev = 0; int temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } // If n is a palindrome return rev == temp;} // Driver Codepublic static void Main(string[] args){ int L = 98, R = 112; int K = 13; Console.WriteLine(countNumbers(L, R, K));}} // This code is contributed by avijitmondal1998", "e": 37558, "s": 35234, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to search the// rightmost index of given numberfunction search(list, num){ var low = 0, high = list.length - 1; // Store the rightmost index var ans = -1; while (low <= high) { // Calculate the mid var mid = low + (high - low) / 2; // If given number <= num if (list[mid] <= num) { // Assign ans = mid ans = mid; // Update low low = mid + 1; } else // Update high high = mid - 1; } // return ans return ans;} // Function to check if the given// number is palindrome or notfunction isPalindrome(n){ var rev = 0; var temp = n; // Generate reverse // of the given number while (n > 0) { rev = rev * 10 + n % 10; n = parseInt(n/10); } // If n is a palindrome return rev == temp;} // Function to find the maximum size// of group of palindrome numbers// having difference between maximum// and minimum element at most Kfunction countNumbers(L, R, K){ // Stores the all the palindromic // numbers in the range [L, R] var list = []; // Traverse over the range [L, R] for(var i = L; i <= R; i++) { // If i is a palindrome if (isPalindrome(i)) { // Append the number // in the list list.push(i); } } // Stores count of maximum // palindromic numbers var count = 0; // Iterate each element in the list for(var i = 0; i < list.length; i++) { // Calculate rightmost index in // the list < current element + K var right_index = search(list, list[i] + K - 1); // Check if there is rightmost // index from the current index if (right_index != -1) count = Math.max(count, right_index - i + 1); } // Return the count return count;} // Driver Codevar L = 98, R = 112;var K = 13;document.write( countNumbers(L, R, K)); // This code is contributed by noob2000.</script>", "e": 39721, "s": 37558, "text": null }, { "code": null, "e": 39723, "s": 39721, "text": "3" }, { "code": null, "e": 39791, "s": 39725, "text": "Time Complexity: O((R – L) * log(R – L))Auxiliary Space: O(R – L)" }, { "code": null, "e": 39808, "s": 39793, "text": "mohit kumar 29" }, { "code": null, "e": 39825, "s": 39808, "text": "avijitmondal1998" }, { "code": null, "e": 39836, "s": 39825, "text": "ipg2016107" }, { "code": null, "e": 39845, "s": 39836, "text": "noob2000" }, { "code": null, "e": 39854, "s": 39845, "text": "sooda367" }, { "code": null, "e": 39863, "s": 39854, "text": "sweetyty" }, { "code": null, "e": 39878, "s": 39863, "text": "adnanirshad158" }, { "code": null, "e": 39889, "s": 39878, "text": "palindrome" }, { "code": null, "e": 39897, "s": 39889, "text": "Reverse" }, { "code": null, "e": 39910, "s": 39897, "text": "Mathematical" }, { "code": null, "e": 39920, "s": 39910, "text": "Searching" }, { "code": null, "e": 39930, "s": 39920, "text": "Searching" }, { "code": null, "e": 39943, "s": 39930, "text": "Mathematical" }, { "code": null, "e": 39954, "s": 39943, "text": "palindrome" }, { "code": null, "e": 39962, "s": 39954, "text": "Reverse" }, { "code": null, "e": 40060, "s": 39962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40104, "s": 40060, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 40146, "s": 40104, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 40177, "s": 40146, "text": "Modular multiplicative inverse" }, { "code": null, "e": 40248, "s": 40177, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 40273, "s": 40248, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 40287, "s": 40273, "text": "Binary Search" }, { "code": null, "e": 40355, "s": 40287, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40369, "s": 40355, "text": "Linear Search" }, { "code": null, "e": 40417, "s": 40369, "text": "Search an element in a sorted and rotated array" } ]
How to Post Data to API using Volley in Android? - GeeksforGeeks
14 Apr, 2022 We have seen reading the data from API using Volley request with the help of GET request in Android. With the help of GET Request, we can display data from API in JSON format and use that data inside our application. In this article, we will take a look at posting our data to API using the POST request with the Volley library in Android. We will be building a simple application in which we will be displaying two EditText fields and for name and a job and we will take that data from our users and post that data to our API. For this, we are using a sample that requires API which is available free for testing. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Data can be added to API in different formats such as XML, Form, and JSON. Most of the APIs post their data in JSON format. So we will also be posting our data to our API in the form of the JSON object. 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: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. implementation ‘com.android.volley:volley:1.1.1’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part. Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it. XML <!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><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" tools:context=".MainActivity"> <!--edit text field for adding name--> <EditText android:id="@+id/idEdtName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_marginTop="40dp" android:hint="Enter your name" /> <!--edit text for adding job--> <EditText android:id="@+id/idEdtJob" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter your job" /> <!--button for adding data--> <Button android:id="@+id/idBtnPost" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Send Data to API" android:textAllCaps="false" /> <!--text view for displaying our API response--> <TextView android:id="@+id/idTVResponse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:gravity="center_horizontal" android:text="Response" android:textAlignment="center" android:textSize="15sp" /> <!--progress bar for loading --> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" /> </LinearLayout> Step 5: 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.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating variables for our edittext, // button, textview and progressbar. private EditText nameEdt, jobEdt; private Button postDataBtn; private TextView responseTV; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views nameEdt = findViewById(R.id.idEdtName); jobEdt = findViewById(R.id.idEdtJob); postDataBtn = findViewById(R.id.idBtnPost); responseTV = findViewById(R.id.idTVResponse); loadingPB = findViewById(R.id.idLoadingPB); // adding on click listener to our button. postDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // validating if the text field is empty or not. if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) { Toast.makeText(MainActivity.this, "Please enter both the values", Toast.LENGTH_SHORT).show(); return; } // calling a method to post the data and passing our name and job. postDataUsingVolley(nameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void postDataUsingVolley(String name, String job) { // url to post our data String url = "https://reqres.in/api/users"; loadingPB.setVisibility(View.VISIBLE); // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are calling a string // request method to post the data to our API // in this we are calling a post method. StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { // inside on response method we are // hiding our progress bar // and setting data to edit text as empty loadingPB.setVisibility(View.GONE); nameEdt.setText(""); jobEdt.setText(""); // on below line we are displaying a success toast message. Toast.makeText(MainActivity.this, "Data added to API", Toast.LENGTH_SHORT).show(); try { // on below line we are parsing the response // to json object to extract data from it. JSONObject respObj = new JSONObject(response); // below are the strings which we // extract from our json object. String name = respObj.getString("name"); String job = respObj.getString("job"); // on below line we are setting this string s to our text view. responseTV.setText("Name : " + name + "\n" + "Job : " + job); } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { // below line we are creating a map for // storing our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put("name", name); params.put("job", job); // at last we are // returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }} Now run your app and see the output of the app by adding the data. anuragatiit android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26406, "s": 26378, "text": "\n14 Apr, 2022" }, { "code": null, "e": 26747, "s": 26406, "text": "We have seen reading the data from API using Volley request with the help of GET request in Android. With the help of GET Request, we can display data from API in JSON format and use that data inside our application. In this article, we will take a look at posting our data to API using the POST request with the Volley library in Android. " }, { "code": null, "e": 27189, "s": 26747, "text": "We will be building a simple application in which we will be displaying two EditText fields and for name and a job and we will take that data from our users and post that data to our API. For this, we are using a sample that requires API which is available free for testing. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 27394, "s": 27189, "text": "Data can be added to API in different formats such as XML, Form, and JSON. Most of the APIs post their data in JSON format. So we will also be posting our data to our API in the form of the JSON object. " }, { "code": null, "e": 27423, "s": 27394, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27585, "s": 27423, "text": "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." }, { "code": null, "e": 27644, "s": 27585, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 27872, "s": 27644, "text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 27921, "s": 27872, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 28021, "s": 27921, "text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. " }, { "code": null, "e": 28096, "s": 28021, "text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file" }, { "code": null, "e": 28170, "s": 28096, "text": "Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 28174, "s": 28170, "text": "XML" }, { "code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 28267, "s": 28174, "text": null }, { "code": null, "e": 28315, "s": 28267, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 28458, "s": 28315, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 28462, "s": 28458, "text": "XML" }, { "code": "<?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\" tools:context=\".MainActivity\"> <!--edit text field for adding name--> <EditText android:id=\"@+id/idEdtName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_marginTop=\"40dp\" android:hint=\"Enter your name\" /> <!--edit text for adding job--> <EditText android:id=\"@+id/idEdtJob\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter your job\" /> <!--button for adding data--> <Button android:id=\"@+id/idBtnPost\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:text=\"Send Data to API\" android:textAllCaps=\"false\" /> <!--text view for displaying our API response--> <TextView android:id=\"@+id/idTVResponse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:gravity=\"center_horizontal\" android:text=\"Response\" android:textAlignment=\"center\" android:textSize=\"15sp\" /> <!--progress bar for loading --> <ProgressBar android:id=\"@+id/idLoadingPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:visibility=\"gone\" /> </LinearLayout>", "e": 30234, "s": 28462, "text": null }, { "code": null, "e": 30282, "s": 30234, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 30472, "s": 30282, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 30477, "s": 30472, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating variables for our edittext, // button, textview and progressbar. private EditText nameEdt, jobEdt; private Button postDataBtn; private TextView responseTV; private ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views nameEdt = findViewById(R.id.idEdtName); jobEdt = findViewById(R.id.idEdtJob); postDataBtn = findViewById(R.id.idBtnPost); responseTV = findViewById(R.id.idTVResponse); loadingPB = findViewById(R.id.idLoadingPB); // adding on click listener to our button. postDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // validating if the text field is empty or not. if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) { Toast.makeText(MainActivity.this, \"Please enter both the values\", Toast.LENGTH_SHORT).show(); return; } // calling a method to post the data and passing our name and job. postDataUsingVolley(nameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void postDataUsingVolley(String name, String job) { // url to post our data String url = \"https://reqres.in/api/users\"; loadingPB.setVisibility(View.VISIBLE); // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are calling a string // request method to post the data to our API // in this we are calling a post method. StringRequest request = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { // inside on response method we are // hiding our progress bar // and setting data to edit text as empty loadingPB.setVisibility(View.GONE); nameEdt.setText(\"\"); jobEdt.setText(\"\"); // on below line we are displaying a success toast message. Toast.makeText(MainActivity.this, \"Data added to API\", Toast.LENGTH_SHORT).show(); try { // on below line we are parsing the response // to json object to extract data from it. JSONObject respObj = new JSONObject(response); // below are the strings which we // extract from our json object. String name = respObj.getString(\"name\"); String job = respObj.getString(\"job\"); // on below line we are setting this string s to our text view. responseTV.setText(\"Name : \" + name + \"\\n\" + \"Job : \" + job); } catch (JSONException e) { e.printStackTrace(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // method to handle errors. Toast.makeText(MainActivity.this, \"Fail to get response = \" + error, Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { // below line we are creating a map for // storing our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put(\"name\", name); params.put(\"job\", job); // at last we are // returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }}", "e": 35411, "s": 30477, "text": null }, { "code": null, "e": 35479, "s": 35411, "text": "Now run your app and see the output of the app by adding the data. " }, { "code": null, "e": 35491, "s": 35479, "text": "anuragatiit" }, { "code": null, "e": 35499, "s": 35491, "text": "android" }, { "code": null, "e": 35523, "s": 35499, "text": "Technical Scripter 2020" }, { "code": null, "e": 35531, "s": 35523, "text": "Android" }, { "code": null, "e": 35536, "s": 35531, "text": "Java" }, { "code": null, "e": 35555, "s": 35536, "text": "Technical Scripter" }, { "code": null, "e": 35560, "s": 35555, "text": "Java" }, { "code": null, "e": 35568, "s": 35560, "text": "Android" }, { "code": null, "e": 35666, "s": 35568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35704, "s": 35666, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35743, "s": 35704, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35793, "s": 35743, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 35844, "s": 35793, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 35886, "s": 35844, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35901, "s": 35886, "text": "Arrays in Java" }, { "code": null, "e": 35945, "s": 35901, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35967, "s": 35945, "text": "For-each loop in Java" }, { "code": null, "e": 36018, "s": 35967, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Browser Automation Using Selenium - GeeksforGeeks
01 Dec, 2020 Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Mastering Selenium will help you automate your day to day tasks like controlling your tweets, Whatsapp texting, and even just googling without actually opening a browser in just 15-30 lines of python code. The limits of automation are endless with selenium. Installation 1.1 Selenium Bindings in PythonSelenium Python bindings provide a convenient API to access Selenium Web Driver like Firefox,Chrome,etc. Pip install Selenium 1.2 Web DriversSelenium requires a web driver to interface with the chosen browser. Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice. Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads Firefox: https://github.com/mozilla/geckodriver/releases Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/ Getting Started from selenium import webdriver # For using sleep function because selenium # works only when the all the elements of the # page is loaded.import time from selenium.webdriver.common.keys import Keys # Creating an instance webdriverbrowser = webdriver.Firefox() browser.get('https://www.twitter.com') # Let's the user see and also load the element time.sleep(2) login = browser.find_elements_by_xpath('//*[@id="doc"]/div[1]/div/div[1]/div[2]/a[3]') # using the click function which is similar to a click in the mouse.login[0].click() print("Login in Twitter") user = browser.find_elements_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/div[1]/input') # Enter User Nameuser[0].send_keys('USER-NAME') user = browser.find_element_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/div[2]/input') # Reads password from a text file because# saving the password in a script is just silly.with open('test.txt', 'r') as myfile: Password = myfile.read().replace('\n', '')user.send_keys(Password) LOG = browser.find_elements_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/input[1]')LOG[0].click()print("Login Successful")time.sleep(5) elem = browser.find_element_by_name("q")elem.click()elem.clear() elem.send_keys("Geeks for geeks ") # using keys to send special KEYS elem.send_keys(Keys.RETURN) print("Search Successful") # closing the browserbrowser.close() Dissecting the code The above script is for logging into twitter and searching for geeks for geeks handle.So let’s see how it works:1. Opening the browser2. Creating a browser instance and using the .get function to connect the website.3. Finding the element this can be anything finding the input box or a button and using the selenium function like click(), send_keys(), etc to interact with the element.4. Closing the browser As of now you must have realized this automation script works in an iterative manner of finding an element and interacting with it. There are various ways of finding an element in the web page, you just right click and inspect element and copy element either by name, css selector or xpath. Well that’s basically it using this you can create a custom automated script for every single website or a universal one for all your social media which automates all your actions.There is no limit to automation and the above is just an example to get you guys started.So happy coding ! Related Post :Whatsapp using Python! This article is contributed by Pradhvan Bisht. 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. nidhi_biet Python-projects python-utility selenium Twitter GBlog Project Python Technical Scripter Twitter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Supervised and Unsupervised learning Introduction to Recurrent Neural Network 12 pip Commands For Python Developers SDE SHEET - A Complete Guide for SDE Preparation Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup
[ { "code": null, "e": 26317, "s": 26289, "text": "\n01 Dec, 2020" }, { "code": null, "e": 26561, "s": 26317, "text": "Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python." }, { "code": null, "e": 26819, "s": 26561, "text": "Mastering Selenium will help you automate your day to day tasks like controlling your tweets, Whatsapp texting, and even just googling without actually opening a browser in just 15-30 lines of python code. The limits of automation are endless with selenium." }, { "code": null, "e": 26832, "s": 26819, "text": "Installation" }, { "code": null, "e": 26968, "s": 26832, "text": "1.1 Selenium Bindings in PythonSelenium Python bindings provide a convenient API to access Selenium Web Driver like Firefox,Chrome,etc." }, { "code": null, "e": 26991, "s": 26968, "text": "Pip install Selenium \n" }, { "code": null, "e": 27307, "s": 26991, "text": "1.2 Web DriversSelenium requires a web driver to interface with the chosen browser. Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice." }, { "code": null, "e": 27511, "s": 27307, "text": "Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads\nFirefox: https://github.com/mozilla/geckodriver/releases\nSafari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/\n" }, { "code": null, "e": 27527, "s": 27511, "text": "Getting Started" }, { "code": "from selenium import webdriver # For using sleep function because selenium # works only when the all the elements of the # page is loaded.import time from selenium.webdriver.common.keys import Keys # Creating an instance webdriverbrowser = webdriver.Firefox() browser.get('https://www.twitter.com') # Let's the user see and also load the element time.sleep(2) login = browser.find_elements_by_xpath('//*[@id=\"doc\"]/div[1]/div/div[1]/div[2]/a[3]') # using the click function which is similar to a click in the mouse.login[0].click() print(\"Login in Twitter\") user = browser.find_elements_by_xpath('//*[@id=\"login-dialog-dialog\"]/div[2]/div[2]/div[2]/form/div[1]/input') # Enter User Nameuser[0].send_keys('USER-NAME') user = browser.find_element_by_xpath('//*[@id=\"login-dialog-dialog\"]/div[2]/div[2]/div[2]/form/div[2]/input') # Reads password from a text file because# saving the password in a script is just silly.with open('test.txt', 'r') as myfile: Password = myfile.read().replace('\\n', '')user.send_keys(Password) LOG = browser.find_elements_by_xpath('//*[@id=\"login-dialog-dialog\"]/div[2]/div[2]/div[2]/form/input[1]')LOG[0].click()print(\"Login Successful\")time.sleep(5) elem = browser.find_element_by_name(\"q\")elem.click()elem.clear() elem.send_keys(\"Geeks for geeks \") # using keys to send special KEYS elem.send_keys(Keys.RETURN) print(\"Search Successful\") # closing the browserbrowser.close() ", "e": 28965, "s": 27527, "text": null }, { "code": null, "e": 28985, "s": 28965, "text": "Dissecting the code" }, { "code": null, "e": 29394, "s": 28985, "text": "The above script is for logging into twitter and searching for geeks for geeks handle.So let’s see how it works:1. Opening the browser2. Creating a browser instance and using the .get function to connect the website.3. Finding the element this can be anything finding the input box or a button and using the selenium function like click(), send_keys(), etc to interact with the element.4. Closing the browser" }, { "code": null, "e": 29685, "s": 29394, "text": "As of now you must have realized this automation script works in an iterative manner of finding an element and interacting with it. There are various ways of finding an element in the web page, you just right click and inspect element and copy element either by name, css selector or xpath." }, { "code": null, "e": 29972, "s": 29685, "text": "Well that’s basically it using this you can create a custom automated script for every single website or a universal one for all your social media which automates all your actions.There is no limit to automation and the above is just an example to get you guys started.So happy coding !" }, { "code": null, "e": 30009, "s": 29972, "text": "Related Post :Whatsapp using Python!" }, { "code": null, "e": 30311, "s": 30009, "text": "This article is contributed by Pradhvan Bisht. 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": 30436, "s": 30311, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30447, "s": 30436, "text": "nidhi_biet" }, { "code": null, "e": 30463, "s": 30447, "text": "Python-projects" }, { "code": null, "e": 30478, "s": 30463, "text": "python-utility" }, { "code": null, "e": 30487, "s": 30478, "text": "selenium" }, { "code": null, "e": 30495, "s": 30487, "text": "Twitter" }, { "code": null, "e": 30501, "s": 30495, "text": "GBlog" }, { "code": null, "e": 30509, "s": 30501, "text": "Project" }, { "code": null, "e": 30516, "s": 30509, "text": "Python" }, { "code": null, "e": 30535, "s": 30516, "text": "Technical Scripter" }, { "code": null, "e": 30543, "s": 30535, "text": "Twitter" }, { "code": null, "e": 30641, "s": 30543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30666, "s": 30641, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30693, "s": 30666, "text": "How to Start Learning DSA?" }, { "code": null, "e": 30730, "s": 30693, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 30771, "s": 30730, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 30809, "s": 30771, "text": "12 pip Commands For Python Developers" }, { "code": null, "e": 30858, "s": 30809, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30891, "s": 30858, "text": "Working with zip files in Python" }, { "code": null, "e": 30913, "s": 30891, "text": "XML parsing in Python" }, { "code": null, "e": 30958, "s": 30913, "text": "Python | Simple GUI calculator using Tkinter" } ]
Prefix matching in Python using pytrie module - GeeksforGeeks
23 Nov, 2020 Given a list of strings and a prefix value sub-string, find all strings from given list of strings which contains given value as prefix ? Examples: Input : arr = ['geeksforgeeks', 'forgeeks', 'geeks', 'eeksfor'], prefix = 'geek' Output : ['geeksforgeeks','geeks'] A Simple approach to solve this problem is to traverse through complete list and match given prefix with each string one by one, print all strings which contains given value as prefix. We have existing solution to solve this problem using Trie Data Structure. We can implement Trie in python using pytrie.StringTrie() module. Create : trie=pytrie.StringTrie() creates a empty trie data structure. Insert : trie[key]=value, key is the data we want to insert in trie and value is similar to bucket which gets appended just after the last node of inserted key and this bucket contains the actual value of key inserted. Search : trie.values(prefix), returns list of all keys which contains given prefix. Delete : del trie[key], removes specified key from trie data structure. Note : To install pytrie package use this pip install pytrie –user command from terminal in linux. # Function which returns all strings # that contains given prefix from pytrie import StringTrie def prefixSearch(arr,prefix): # create empty trie trie=StringTrie() # traverse through list of strings # to insert it in trie. Here value of # key is itself key because at last # we need to return for key in arr: trie[key] = key # values(search) method returns list # of values of keys which contains # search pattern as prefix return trie.values(prefix) # Driver program if __name__ == "__main__": arr = ['geeksforgeeks','forgeeks','geeks','eeksfor'] prefix = 'geek' output = prefixSearch(arr,prefix) if len(output) > 0: print (output) else: print ('Pattern not found') Output: ['geeksforgeeks','geeks'] This article is contributed by Shashank Mishra (Gullu). 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 Strings Strings 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 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25579, "s": 25551, "text": "\n23 Nov, 2020" }, { "code": null, "e": 25717, "s": 25579, "text": "Given a list of strings and a prefix value sub-string, find all strings from given list of strings which contains given value as prefix ?" }, { "code": null, "e": 25727, "s": 25717, "text": "Examples:" }, { "code": null, "e": 25868, "s": 25727, "text": "Input : arr = ['geeksforgeeks', 'forgeeks', \n 'geeks', 'eeksfor'], \n prefix = 'geek'\nOutput : ['geeksforgeeks','geeks']\n" }, { "code": null, "e": 26053, "s": 25868, "text": "A Simple approach to solve this problem is to traverse through complete list and match given prefix with each string one by one, print all strings which contains given value as prefix." }, { "code": null, "e": 26194, "s": 26053, "text": "We have existing solution to solve this problem using Trie Data Structure. We can implement Trie in python using pytrie.StringTrie() module." }, { "code": null, "e": 26265, "s": 26194, "text": "Create : trie=pytrie.StringTrie() creates a empty trie data structure." }, { "code": null, "e": 26484, "s": 26265, "text": "Insert : trie[key]=value, key is the data we want to insert in trie and value is similar to bucket which gets appended just after the last node of inserted key and this bucket contains the actual value of key inserted." }, { "code": null, "e": 26568, "s": 26484, "text": "Search : trie.values(prefix), returns list of all keys which contains given prefix." }, { "code": null, "e": 26640, "s": 26568, "text": "Delete : del trie[key], removes specified key from trie data structure." }, { "code": null, "e": 26739, "s": 26640, "text": "Note : To install pytrie package use this pip install pytrie –user command from terminal in linux." }, { "code": "# Function which returns all strings # that contains given prefix from pytrie import StringTrie def prefixSearch(arr,prefix): # create empty trie trie=StringTrie() # traverse through list of strings # to insert it in trie. Here value of # key is itself key because at last # we need to return for key in arr: trie[key] = key # values(search) method returns list # of values of keys which contains # search pattern as prefix return trie.values(prefix) # Driver program if __name__ == \"__main__\": arr = ['geeksforgeeks','forgeeks','geeks','eeksfor'] prefix = 'geek' output = prefixSearch(arr,prefix) if len(output) > 0: print (output) else: print ('Pattern not found')", "e": 27507, "s": 26739, "text": null }, { "code": null, "e": 27515, "s": 27507, "text": "Output:" }, { "code": null, "e": 27541, "s": 27515, "text": "['geeksforgeeks','geeks']" }, { "code": null, "e": 27852, "s": 27541, "text": "This article is contributed by Shashank Mishra (Gullu). 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": 27977, "s": 27852, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27984, "s": 27977, "text": "Python" }, { "code": null, "e": 27992, "s": 27984, "text": "Strings" }, { "code": null, "e": 28000, "s": 27992, "text": "Strings" }, { "code": null, "e": 28098, "s": 28000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28130, "s": 28098, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28172, "s": 28130, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28214, "s": 28172, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28270, "s": 28214, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28297, "s": 28270, "text": "Python Classes and Objects" }, { "code": null, "e": 28343, "s": 28297, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 28368, "s": 28343, "text": "Reverse a string in Java" }, { "code": null, "e": 28428, "s": 28368, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28443, "s": 28428, "text": "C++ Data Types" } ]
Multiplication Table Generator using Python - GeeksforGeeks
25 Feb, 2021 Prerequisites: Python GUI- Tkinter We all know that Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. In this article, we will learn How to create a Times-table using Tkinter. Approach: Import Tkinter Library Create Function of Multiplication Table Create the main window (container) Create Variabletext field that store value of Number Call the function By Generate Table Button Execute code Program: Python #import libraryimport sysfrom tkinter import * def MultiTable(): print("\n:Multiplication Table:\n") print("\nTimes-Table of Number", (EnterTable.get()), '\n') for x in range(1, 13): number = int(EnterTable.get()) print('\t\t', (number), 'x', (x), '=', (x*number),) # Create Main windowTable = Tk()Table.geometry('250x250+700+200')Table.title('Multiplication Table') # Variable DeclarationEnterTable = StringVar() label1 = Label(Table, text='Enter Your Times-table Number:', font=30, fg='Black').grid(row=1, column=6)label1 = Label(Table, text=' ').grid(row=2, column=6) # Store Number in Textvariableentry = Entry(Table, textvariable=EnterTable, justify='center').grid(row=3, column=6)label1 = Label(Table, text=' ').grid(row=4, column=6) # Call the functionbutton1 = Button(Table, text="Generate Table", fg="Blue", command=MultiTable).grid(row=5, column=6)label1 = Label(Table, text=' ').grid(row=6, column=6) # ExitEXIT = Button(Table, text="Quit", fg="red", command=Table.destroy).grid(row=7, column=6) Table.mainloop() Output: Python Tkinter-exercises Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python How to Install PIP on Windows ? Deque in Python Python math function | sqrt() Bar Plot in Matplotlib Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Output Formatting Class method vs Static method in Python
[ { "code": null, "e": 25563, "s": 25535, "text": "\n25 Feb, 2021" }, { "code": null, "e": 25598, "s": 25563, "text": "Prerequisites: Python GUI- Tkinter" }, { "code": null, "e": 25828, "s": 25598, "text": "We all know that Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. In this article, we will learn How to create a Times-table using Tkinter." }, { "code": null, "e": 25838, "s": 25828, "text": "Approach:" }, { "code": null, "e": 25861, "s": 25838, "text": "Import Tkinter Library" }, { "code": null, "e": 25901, "s": 25861, "text": "Create Function of Multiplication Table" }, { "code": null, "e": 25936, "s": 25901, "text": "Create the main window (container)" }, { "code": null, "e": 25989, "s": 25936, "text": "Create Variabletext field that store value of Number" }, { "code": null, "e": 26032, "s": 25989, "text": "Call the function By Generate Table Button" }, { "code": null, "e": 26045, "s": 26032, "text": "Execute code" }, { "code": null, "e": 26054, "s": 26045, "text": "Program:" }, { "code": null, "e": 26061, "s": 26054, "text": "Python" }, { "code": "#import libraryimport sysfrom tkinter import * def MultiTable(): print(\"\\n:Multiplication Table:\\n\") print(\"\\nTimes-Table of Number\", (EnterTable.get()), '\\n') for x in range(1, 13): number = int(EnterTable.get()) print('\\t\\t', (number), 'x', (x), '=', (x*number),) # Create Main windowTable = Tk()Table.geometry('250x250+700+200')Table.title('Multiplication Table') # Variable DeclarationEnterTable = StringVar() label1 = Label(Table, text='Enter Your Times-table Number:', font=30, fg='Black').grid(row=1, column=6)label1 = Label(Table, text=' ').grid(row=2, column=6) # Store Number in Textvariableentry = Entry(Table, textvariable=EnterTable, justify='center').grid(row=3, column=6)label1 = Label(Table, text=' ').grid(row=4, column=6) # Call the functionbutton1 = Button(Table, text=\"Generate Table\", fg=\"Blue\", command=MultiTable).grid(row=5, column=6)label1 = Label(Table, text=' ').grid(row=6, column=6) # ExitEXIT = Button(Table, text=\"Quit\", fg=\"red\", command=Table.destroy).grid(row=7, column=6) Table.mainloop()", "e": 27240, "s": 26061, "text": null }, { "code": null, "e": 27248, "s": 27240, "text": "Output:" }, { "code": null, "e": 27273, "s": 27248, "text": "Python Tkinter-exercises" }, { "code": null, "e": 27288, "s": 27273, "text": "Python-tkinter" }, { "code": null, "e": 27312, "s": 27288, "text": "Technical Scripter 2020" }, { "code": null, "e": 27319, "s": 27312, "text": "Python" }, { "code": null, "e": 27338, "s": 27319, "text": "Technical Scripter" }, { "code": null, "e": 27436, "s": 27338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27458, "s": 27436, "text": "Defaultdict in Python" }, { "code": null, "e": 27490, "s": 27458, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27506, "s": 27490, "text": "Deque in Python" }, { "code": null, "e": 27536, "s": 27506, "text": "Python math function | sqrt()" }, { "code": null, "e": 27559, "s": 27536, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27601, "s": 27559, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27657, "s": 27601, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27684, "s": 27657, "text": "Python Classes and Objects" }, { "code": null, "e": 27711, "s": 27684, "text": "Python | Output Formatting" } ]
How to detect user pressing Home Key in an Activity on Android?
This example demonstrates how do I detect user pressing home key in an activity on 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" android:orientation = "vertical" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/textView" android:layout_width = "fill_parent" android:gravity = "center" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click here" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textView); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onUserLeaveHint(); } }); } @Override protected void onUserLeaveHint(){ textView.setText("Home Button Pressed"); Toast.makeText(MainActivity.this, "Home Button pressed", Toast.LENGTH_SHORT).show(); super.onUserLeaveHint(); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1154, "s": 1062, "text": "This example demonstrates how do I detect user pressing home key in an activity on android." }, { "code": null, "e": 1283, "s": 1154, "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": 1348, "s": 1283, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1866, "s": 1348, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"vertical\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/textView\"\n android:layout_width = \"fill_parent\"\n android:gravity = \"center\"\n android:textSize = \"30sp\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click here\" />\n</LinearLayout>" }, { "code": null, "e": 1923, "s": 1866, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2778, "s": 1923, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = (TextView)findViewById(R.id.textView);\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onUserLeaveHint();\n }\n });\n }\n @Override\n protected void onUserLeaveHint(){\n textView.setText(\"Home Button Pressed\");\n Toast.makeText(MainActivity.this, \"Home Button pressed\", Toast.LENGTH_SHORT).show();\n super.onUserLeaveHint();\n }\n}" }, { "code": null, "e": 2833, "s": 2778, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3503, "s": 2833, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3850, "s": 3503, "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": 3891, "s": 3850, "text": "Click here to download the project code." } ]
wprintf() and wscanf in C Library
Here we will see the wprintf() and wscanf() functions in C. These are the printf() and scanf() functions for wide characters. These functions are present in the wchar.h The wprintf() function is used to print the wide character to the standard output. The wide string format may contain the format specifiers which is starting with % sign, these are replaced by the values of variables which are passed to the wprintf(). The syntax is like below − int wprintf (const wchar_t* format, ...); This function takes the format. This format is a pointer to a null terminated wide string, that will be written in the console. It will hold wide characters and some format specifiers starting with %. Then the (...) is indicating the additional arguments. These are the data that will be printed, they occur in a sequence according to the format specifiers. This function returns the number of printed characters. On failure, this may return negative values. #include <stdio.h> #include <wchar.h> main() { wint_t my_int = 10; wchar_t string[] = L"Hello World"; wprintf(L"The my_int is: %d \n", my_int); wprintf(L"The string is: %ls \n", string); } The my_int is: 10 The string is: Hello World The wscanf() function is used to take the data from console, and store them into proper variable. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier inside the format string. #include <stdio.h> #include <wchar.h> main() { wint_t my_int = 10; wprintf(L"Enter a number: "); wscanf(L"%d", &my_int); wprintf(L"The given integer is: %d \n", my_int); } Enter a number: 40 The given integer is: 40
[ { "code": null, "e": 1231, "s": 1062, "text": "Here we will see the wprintf() and wscanf() functions in C. These are the printf() and scanf() functions for wide characters. These functions are present in the wchar.h" }, { "code": null, "e": 1483, "s": 1231, "text": "The wprintf() function is used to print the wide character to the standard output. The wide string format may contain the format specifiers which is starting with % sign, these are replaced by the values of variables which are passed to the wprintf()." }, { "code": null, "e": 1510, "s": 1483, "text": "The syntax is like below −" }, { "code": null, "e": 1552, "s": 1510, "text": "int wprintf (const wchar_t* format, ...);" }, { "code": null, "e": 1910, "s": 1552, "text": "This function takes the format. This format is a pointer to a null terminated wide string, that will be written in the console. It will hold wide characters and some format specifiers starting with %. Then the (...) is indicating the additional arguments. These are the data that will be printed, they occur in a sequence according to the format specifiers." }, { "code": null, "e": 2011, "s": 1910, "text": "This function returns the number of printed characters. On failure, this may return negative values." }, { "code": null, "e": 2212, "s": 2011, "text": "#include <stdio.h>\n#include <wchar.h>\nmain() {\n wint_t my_int = 10;\n wchar_t string[] = L\"Hello World\";\n wprintf(L\"The my_int is: %d \\n\", my_int);\n wprintf(L\"The string is: %ls \\n\", string);\n}" }, { "code": null, "e": 2257, "s": 2212, "text": "The my_int is: 10\nThe string is: Hello World" }, { "code": null, "e": 2510, "s": 2257, "text": "The wscanf() function is used to take the data from console, and store them into proper variable. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier inside the format string." }, { "code": null, "e": 2694, "s": 2510, "text": "#include <stdio.h>\n#include <wchar.h>\nmain() {\n wint_t my_int = 10;\n wprintf(L\"Enter a number: \");\n wscanf(L\"%d\", &my_int);\n wprintf(L\"The given integer is: %d \\n\", my_int);\n}" }, { "code": null, "e": 2738, "s": 2694, "text": "Enter a number: 40\nThe given integer is: 40" } ]
Schemafull streaming data processing in ML pipelines | by Ivan Senilov | Towards Data Science
In one of my previous articles on Machine Learning pipelines, message queues were touched as an alternative to HTTP client-server architecture which is the most common way to serve ML models nowadays. Just to refresh, here are the advantages of using queues like Apache Kafka in ML pipelines: Naturally asynchronous processing with decoupling of an input data producer and data processor (consumer in Kafka terminology), i.e. failure of ML inference/training service consuming the data will not result in HTTP timeouts, data loss, and failure of the data producer but just in delayed processing Better compute resources utilization for CPU/GPU-bound tasks such as ML inference/training:- Batch inference is usually more efficient as ML models do not need to be warmed up and torn down for every single prediction- The queue smoothens load if incoming data arrives irregularly whereas an HTTP server would be overwhelmed during load peaks and idling during quiet periods Improved throughput. However, it is worth mentioning that queues are not perfect when inference latency is crucial. In these cases, Kafka consumers with a very short polling interval (which removes some of the previous advantages)or HTTP ML model server can still be viable options. It is advised to readers to familiarize themselves with Apache Kafka and Docker (including docker-compose) before proceeding with the article. Confluent has a nice introduction page for Kafka. Docker docs are also great. The majority of tutorials on how to use Kafka, especially with Python, show examples of producing and consuming schemaless JSON strings. Even though it is easy to get those examples running, they are not very suitable for production use. Let’s see why. Producer can’t enforce data format (set of fields) it publishes to a topic which may cause incompatibilities and runtime errors on the consumer side. Of course, it can be handled in the code but it would make the code much more complicated and consequently error-prone and requiring more maintenance. Data format evolution does not have constraints so the producer can potentially switch to a new schema without a field consumer expects which may lead to runtime errors again (see the next section for details) Data in JSON format includes field names with every message which makes it inefficient in terms of storage space Schemafull messages solve these problems, however, it comes with a price of more complicated infrastructure and required carefulness with schema evolution. Kafka supports AVRO, Protobuf, and JSON-schema (this still has the drawback of JSON data format being non-binary and not very efficient in terms of storage). We will use AVRO in the article’s code as this seems to be the most common schema format for Kafka. Once defined, schema usually can’t be arbitrarily changed. One mentioned example is field removal or renaming. This potential issue can be solved by defining fields as nullable and with default value so if the field becomes obsolete — the producer just stops populating it while it remains in the new updated version of the schema: {"name": "value", "type": ["null", "double"], "default": null} Other schema evolution considerations are described in the AVRO specification. This repository has a basic example of Python AVRO consumer and producer: github.com Let’s review the services it consists of looking at services section of docker-compose.yaml Apache ZooKeeper is used by Kafka for maintaining configuration in a centralized location and is a prerequisite for a working Kafka cluster. Consumers and producers usually do not interact with it directly so we omit its detailed description here. Confluent Schema Registry is a service for storing and retrieving schemas. Apparently, one can use Kafka without it just having schemas together with application code but the schema registry ensures a single source of truth for versioned schemas across all the consumers and producers excluding the possibility of schemas deviation between those. The registry has both RESTful API as well as native support by confluent-kafka-client which is defacto standard for working with Kafka in Python. Registering a schema with the HTTP request can be done like this: SCHEMA=$(sed 's/"/\\"/g' < ./Message.avsc)curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \ --data "{\"schema\":\"${SCHEMA//$'\n'}\"}" \ http://<registry_host>:<registry_port>/subjects/<name>/versions It should return the id (version) the schema was registered with: {“id”:1} Using the schema from Python code can be done by instantiating AvroSerializer and AvroDeserializer from the aforementioned client. Apache Kafka cluster itself is run using a Docker image from Confluent which has everything needed for its operation.It has a lot of configuration options but we limit ourselves to basic working options, for example, PLAINTEXT protocol that does not perform any encryption. This is a short-lived instance of Kafka used solely for the creation of the topic we plan to use in the demo with kafka-topics CLI: kafka-topics --create --if-not-exists --topic Test.Topic --bootstrap-server kafka:29092 --replication-factor 1 --partitions 1 replication-factor and partitions options are set to 1 for simplicity. Refer to Kafka documentation for more details on these and many more other options. This is the consuming and producing app itself. Both consumer and producer are in the __main__.py for simplicity. The code is mostly self-explanatory so let’s look only at some important parts of it. The producer configuration: "value.serializer": AvroSerializer(schema_str=Message.schema,schema_registry_client=schema_registry_client, to_dict=todict) schema_str=Message.schema — producer requires passing a schema and here we pass the property of generated Python class that contains the schema. The schema will be uploaded and registered in schema_registry_client . to_dict=todict — this must be a callable that converts the message object to a Python dictionary. We use todict method from helpers.py from generated code. The consumer configuration: "value.deserializer": AvroDeserializer(schema_str=None, schema_registry_client=schema_registry_client,from_dict=lambda obj, _: Message(obj)) Here we don’t pass the schema so the schema_registry_client will fetch it from the schema registry.from_dict=lambda obj, _: Message(obj) — the opposite operation of converting a dictionary to a message object. We need to perform a little hack here because the deserializer passes context as a second argument to the callable (which we ignore) but the generated class constructor accepts only the dictionary. "group.id": "test_group" “group.id”. This allows multiple consumers (read multiple containers with data processing apps for horizontal scaling) sharing the same consumer group ID to consume messages in turns as they share the Kafka offset. At the same time, if one needs to use the messages for another purpose, for example, test an experimental ML model online, it can be done by deploying this experimental group with a new group.id avoiding messing up with the main production formation. The repository’s README.md has instructions for running the whole bunch of services with docker-compose . Executing the commands should result in something like this in stdout: worker_1 | Waiting for schema registry to be availableworker_1 | Producing message to topic 'Test.Topic'worker_1 | Produced message: {'timestamp': 1639304378, 'data': {'count': 10, 'value': 100.0}}worker_1 | worker_1 | Flushing records...worker_1 | Consumed message: {'timestamp': 1639304378, 'data': {'count': 10, 'value': 100.0}} Which means producing and consuming was performed successfully. We print the consumed message: if message is not None: print(f"Consumed message: {message.dict()}") but this is where inference code usually goes with subsequent publishing the resulting predictions to another topic, saving them to a database or using them in a downstream API call. In general, monitoring of the Kafka consuming ML service is similar to what was described in the Complete Machine Learning pipeline for NLP tasks article. However, inference time can (and probably should) be accompanied by the consumer lag which shows how much the consumer is behind the published data. If it grows, it usually means the consumer formation must be scaled. When using a librdkafka-based client, like confluent-kafka-python used in this example, consumer lag can be obtained using statistics returned by librdkafka as explained in this issue. The article shows why using schemas with Kafka might be a good idea and how it can be implemented using Python, the language of choice for ML services. As always, if you have any questions or suggestions regarding the content — please do not hesitate to reach me on LinkedIn.
[ { "code": null, "e": 373, "s": 172, "text": "In one of my previous articles on Machine Learning pipelines, message queues were touched as an alternative to HTTP client-server architecture which is the most common way to serve ML models nowadays." }, { "code": null, "e": 465, "s": 373, "text": "Just to refresh, here are the advantages of using queues like Apache Kafka in ML pipelines:" }, { "code": null, "e": 767, "s": 465, "text": "Naturally asynchronous processing with decoupling of an input data producer and data processor (consumer in Kafka terminology), i.e. failure of ML inference/training service consuming the data will not result in HTTP timeouts, data loss, and failure of the data producer but just in delayed processing" }, { "code": null, "e": 1142, "s": 767, "text": "Better compute resources utilization for CPU/GPU-bound tasks such as ML inference/training:- Batch inference is usually more efficient as ML models do not need to be warmed up and torn down for every single prediction- The queue smoothens load if incoming data arrives irregularly whereas an HTTP server would be overwhelmed during load peaks and idling during quiet periods" }, { "code": null, "e": 1425, "s": 1142, "text": "Improved throughput. However, it is worth mentioning that queues are not perfect when inference latency is crucial. In these cases, Kafka consumers with a very short polling interval (which removes some of the previous advantages)or HTTP ML model server can still be viable options." }, { "code": null, "e": 1646, "s": 1425, "text": "It is advised to readers to familiarize themselves with Apache Kafka and Docker (including docker-compose) before proceeding with the article. Confluent has a nice introduction page for Kafka. Docker docs are also great." }, { "code": null, "e": 1899, "s": 1646, "text": "The majority of tutorials on how to use Kafka, especially with Python, show examples of producing and consuming schemaless JSON strings. Even though it is easy to get those examples running, they are not very suitable for production use. Let’s see why." }, { "code": null, "e": 2200, "s": 1899, "text": "Producer can’t enforce data format (set of fields) it publishes to a topic which may cause incompatibilities and runtime errors on the consumer side. Of course, it can be handled in the code but it would make the code much more complicated and consequently error-prone and requiring more maintenance." }, { "code": null, "e": 2410, "s": 2200, "text": "Data format evolution does not have constraints so the producer can potentially switch to a new schema without a field consumer expects which may lead to runtime errors again (see the next section for details)" }, { "code": null, "e": 2523, "s": 2410, "text": "Data in JSON format includes field names with every message which makes it inefficient in terms of storage space" }, { "code": null, "e": 2679, "s": 2523, "text": "Schemafull messages solve these problems, however, it comes with a price of more complicated infrastructure and required carefulness with schema evolution." }, { "code": null, "e": 2937, "s": 2679, "text": "Kafka supports AVRO, Protobuf, and JSON-schema (this still has the drawback of JSON data format being non-binary and not very efficient in terms of storage). We will use AVRO in the article’s code as this seems to be the most common schema format for Kafka." }, { "code": null, "e": 3269, "s": 2937, "text": "Once defined, schema usually can’t be arbitrarily changed. One mentioned example is field removal or renaming. This potential issue can be solved by defining fields as nullable and with default value so if the field becomes obsolete — the producer just stops populating it while it remains in the new updated version of the schema:" }, { "code": null, "e": 3332, "s": 3269, "text": "{\"name\": \"value\", \"type\": [\"null\", \"double\"], \"default\": null}" }, { "code": null, "e": 3411, "s": 3332, "text": "Other schema evolution considerations are described in the AVRO specification." }, { "code": null, "e": 3485, "s": 3411, "text": "This repository has a basic example of Python AVRO consumer and producer:" }, { "code": null, "e": 3496, "s": 3485, "text": "github.com" }, { "code": null, "e": 3588, "s": 3496, "text": "Let’s review the services it consists of looking at services section of docker-compose.yaml" }, { "code": null, "e": 3836, "s": 3588, "text": "Apache ZooKeeper is used by Kafka for maintaining configuration in a centralized location and is a prerequisite for a working Kafka cluster. Consumers and producers usually do not interact with it directly so we omit its detailed description here." }, { "code": null, "e": 4183, "s": 3836, "text": "Confluent Schema Registry is a service for storing and retrieving schemas. Apparently, one can use Kafka without it just having schemas together with application code but the schema registry ensures a single source of truth for versioned schemas across all the consumers and producers excluding the possibility of schemas deviation between those." }, { "code": null, "e": 4329, "s": 4183, "text": "The registry has both RESTful API as well as native support by confluent-kafka-client which is defacto standard for working with Kafka in Python." }, { "code": null, "e": 4395, "s": 4329, "text": "Registering a schema with the HTTP request can be done like this:" }, { "code": null, "e": 4621, "s": 4395, "text": "SCHEMA=$(sed 's/\"/\\\\\"/g' < ./Message.avsc)curl -X POST -H \"Content-Type: application/vnd.schemaregistry.v1+json\" \\ --data \"{\\\"schema\\\":\\\"${SCHEMA//$'\\n'}\\\"}\" \\ http://<registry_host>:<registry_port>/subjects/<name>/versions" }, { "code": null, "e": 4696, "s": 4621, "text": "It should return the id (version) the schema was registered with: {“id”:1}" }, { "code": null, "e": 4827, "s": 4696, "text": "Using the schema from Python code can be done by instantiating AvroSerializer and AvroDeserializer from the aforementioned client." }, { "code": null, "e": 5101, "s": 4827, "text": "Apache Kafka cluster itself is run using a Docker image from Confluent which has everything needed for its operation.It has a lot of configuration options but we limit ourselves to basic working options, for example, PLAINTEXT protocol that does not perform any encryption." }, { "code": null, "e": 5233, "s": 5101, "text": "This is a short-lived instance of Kafka used solely for the creation of the topic we plan to use in the demo with kafka-topics CLI:" }, { "code": null, "e": 5359, "s": 5233, "text": "kafka-topics --create --if-not-exists --topic Test.Topic --bootstrap-server kafka:29092 --replication-factor 1 --partitions 1" }, { "code": null, "e": 5514, "s": 5359, "text": "replication-factor and partitions options are set to 1 for simplicity. Refer to Kafka documentation for more details on these and many more other options." }, { "code": null, "e": 5714, "s": 5514, "text": "This is the consuming and producing app itself. Both consumer and producer are in the __main__.py for simplicity. The code is mostly self-explanatory so let’s look only at some important parts of it." }, { "code": null, "e": 5742, "s": 5714, "text": "The producer configuration:" }, { "code": null, "e": 5866, "s": 5742, "text": "\"value.serializer\": AvroSerializer(schema_str=Message.schema,schema_registry_client=schema_registry_client, to_dict=todict)" }, { "code": null, "e": 6082, "s": 5866, "text": "schema_str=Message.schema — producer requires passing a schema and here we pass the property of generated Python class that contains the schema. The schema will be uploaded and registered in schema_registry_client ." }, { "code": null, "e": 6238, "s": 6082, "text": "to_dict=todict — this must be a callable that converts the message object to a Python dictionary. We use todict method from helpers.py from generated code." }, { "code": null, "e": 6266, "s": 6238, "text": "The consumer configuration:" }, { "code": null, "e": 6407, "s": 6266, "text": "\"value.deserializer\": AvroDeserializer(schema_str=None, schema_registry_client=schema_registry_client,from_dict=lambda obj, _: Message(obj))" }, { "code": null, "e": 6815, "s": 6407, "text": "Here we don’t pass the schema so the schema_registry_client will fetch it from the schema registry.from_dict=lambda obj, _: Message(obj) — the opposite operation of converting a dictionary to a message object. We need to perform a little hack here because the deserializer passes context as a second argument to the callable (which we ignore) but the generated class constructor accepts only the dictionary." }, { "code": null, "e": 6840, "s": 6815, "text": "\"group.id\": \"test_group\"" }, { "code": null, "e": 7306, "s": 6840, "text": "“group.id”. This allows multiple consumers (read multiple containers with data processing apps for horizontal scaling) sharing the same consumer group ID to consume messages in turns as they share the Kafka offset. At the same time, if one needs to use the messages for another purpose, for example, test an experimental ML model online, it can be done by deploying this experimental group with a new group.id avoiding messing up with the main production formation." }, { "code": null, "e": 7483, "s": 7306, "text": "The repository’s README.md has instructions for running the whole bunch of services with docker-compose . Executing the commands should result in something like this in stdout:" }, { "code": null, "e": 7821, "s": 7483, "text": "worker_1 | Waiting for schema registry to be availableworker_1 | Producing message to topic 'Test.Topic'worker_1 | Produced message: {'timestamp': 1639304378, 'data': {'count': 10, 'value': 100.0}}worker_1 | worker_1 | Flushing records...worker_1 | Consumed message: {'timestamp': 1639304378, 'data': {'count': 10, 'value': 100.0}}" }, { "code": null, "e": 7885, "s": 7821, "text": "Which means producing and consuming was performed successfully." }, { "code": null, "e": 7916, "s": 7885, "text": "We print the consumed message:" }, { "code": null, "e": 7988, "s": 7916, "text": "if message is not None: print(f\"Consumed message: {message.dict()}\")" }, { "code": null, "e": 8171, "s": 7988, "text": "but this is where inference code usually goes with subsequent publishing the resulting predictions to another topic, saving them to a database or using them in a downstream API call." }, { "code": null, "e": 8326, "s": 8171, "text": "In general, monitoring of the Kafka consuming ML service is similar to what was described in the Complete Machine Learning pipeline for NLP tasks article." }, { "code": null, "e": 8729, "s": 8326, "text": "However, inference time can (and probably should) be accompanied by the consumer lag which shows how much the consumer is behind the published data. If it grows, it usually means the consumer formation must be scaled. When using a librdkafka-based client, like confluent-kafka-python used in this example, consumer lag can be obtained using statistics returned by librdkafka as explained in this issue." } ]
Lodash _.isNaN() Method - GeeksforGeeks
16 Sep, 2020 The Lodash _.isNaN() Method checks the given value is NaN or not. This method is not the same as the JavaScript isNaN() method which returns true for undefined and other non-number values. Syntax: _.isNaN( value ) Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value that need to be checked for NaN. Return Value: This method returns a Boolean value (Returns true if the value is NaN, else false). Example 1: Javascript // Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(NaN)); Output: true Example 2: For checking with an empty source this method returns true. Javascript // Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(new Number(NaN))); Output: true Example 3: This method also works for arrays. Javascript // Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(undefined)); // Checkingconsole.log(_.isNaN(10)); Output: false false JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24461, "s": 24433, "text": "\n16 Sep, 2020" }, { "code": null, "e": 24650, "s": 24461, "text": "The Lodash _.isNaN() Method checks the given value is NaN or not. This method is not the same as the JavaScript isNaN() method which returns true for undefined and other non-number values." }, { "code": null, "e": 24658, "s": 24650, "text": "Syntax:" }, { "code": null, "e": 24676, "s": 24658, "text": "_.isNaN( value )\n" }, { "code": null, "e": 24767, "s": 24676, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 24838, "s": 24767, "text": "value: This parameter holds the value that need to be checked for NaN." }, { "code": null, "e": 24936, "s": 24838, "text": "Return Value: This method returns a Boolean value (Returns true if the value is NaN, else false)." }, { "code": null, "e": 24948, "s": 24936, "text": "Example 1: " }, { "code": null, "e": 24959, "s": 24948, "text": "Javascript" }, { "code": "// Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(NaN));", "e": 25056, "s": 24959, "text": null }, { "code": null, "e": 25064, "s": 25056, "text": "Output:" }, { "code": null, "e": 25070, "s": 25064, "text": "true\n" }, { "code": null, "e": 25141, "s": 25070, "text": "Example 2: For checking with an empty source this method returns true." }, { "code": null, "e": 25152, "s": 25141, "text": "Javascript" }, { "code": "// Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(new Number(NaN)));", "e": 25261, "s": 25152, "text": null }, { "code": null, "e": 25269, "s": 25261, "text": "Output:" }, { "code": null, "e": 25275, "s": 25269, "text": "true\n" }, { "code": null, "e": 25321, "s": 25275, "text": "Example 3: This method also works for arrays." }, { "code": null, "e": 25332, "s": 25321, "text": "Javascript" }, { "code": "// Defining Lodash variable const _ = require('lodash'); // Checkingconsole.log(_.isNaN(undefined)); // Checkingconsole.log(_.isNaN(10));", "e": 25474, "s": 25332, "text": null }, { "code": null, "e": 25482, "s": 25474, "text": "Output:" }, { "code": null, "e": 25495, "s": 25482, "text": "false\nfalse\n" }, { "code": null, "e": 25513, "s": 25495, "text": "JavaScript-Lodash" }, { "code": null, "e": 25524, "s": 25513, "text": "JavaScript" }, { "code": null, "e": 25541, "s": 25524, "text": "Web Technologies" }, { "code": null, "e": 25639, "s": 25541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25648, "s": 25639, "text": "Comments" }, { "code": null, "e": 25661, "s": 25648, "text": "Old Comments" }, { "code": null, "e": 25722, "s": 25661, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25767, "s": 25722, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 25839, "s": 25767, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 25891, "s": 25839, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 25937, "s": 25891, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 25993, "s": 25937, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26026, "s": 25993, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26088, "s": 26026, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26131, "s": 26088, "text": "How to fetch data from an API in ReactJS ?" } ]
Python List count() Method
Python list method count() returns count of how many times obj occurs in list. Following is the syntax for count() method − list.count(obj) obj − This is the object to be counted in the list. obj − This is the object to be counted in the list. This method returns count of how many times obj occurs in list. The following example shows the usage of count() method. #!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc', 123]; print "Count for 123 : ", aList.count(123) print "Count for zara : ", aList.count('zara') When we run above program, it produces following result − Count for 123 : 2 Count for zara : 1 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": 2323, "s": 2244, "text": "Python list method count() returns count of how many times obj occurs in list." }, { "code": null, "e": 2368, "s": 2323, "text": "Following is the syntax for count() method −" }, { "code": null, "e": 2385, "s": 2368, "text": "list.count(obj)\n" }, { "code": null, "e": 2437, "s": 2385, "text": "obj − This is the object to be counted in the list." }, { "code": null, "e": 2489, "s": 2437, "text": "obj − This is the object to be counted in the list." }, { "code": null, "e": 2553, "s": 2489, "text": "This method returns count of how many times obj occurs in list." }, { "code": null, "e": 2610, "s": 2553, "text": "The following example shows the usage of count() method." }, { "code": null, "e": 2761, "s": 2610, "text": "#!/usr/bin/python\n\naList = [123, 'xyz', 'zara', 'abc', 123];\nprint \"Count for 123 : \", aList.count(123)\nprint \"Count for zara : \", aList.count('zara')" }, { "code": null, "e": 2819, "s": 2761, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2859, "s": 2819, "text": "Count for 123 : 2\nCount for zara : 1\n" }, { "code": null, "e": 2896, "s": 2859, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2912, "s": 2896, "text": " Malhar Lathkar" }, { "code": null, "e": 2945, "s": 2912, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2964, "s": 2945, "text": " Arnab Chakraborty" }, { "code": null, "e": 2999, "s": 2964, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3021, "s": 2999, "text": " In28Minutes Official" }, { "code": null, "e": 3055, "s": 3021, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3083, "s": 3055, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3118, "s": 3083, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3132, "s": 3118, "text": " Lets Kode It" }, { "code": null, "e": 3165, "s": 3132, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3182, "s": 3165, "text": " Abhilash Nelson" }, { "code": null, "e": 3189, "s": 3182, "text": " Print" }, { "code": null, "e": 3200, "s": 3189, "text": " Add Notes" } ]
Difference Between Arrays.toString() and Arrays.deepToString() in Java - GeeksforGeeks
28 Jan, 2021 The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Returns “null” if a is null. In the case of an Object Array, if the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents. Parameters: The array whose string representation to return. Returns: The string representation of the array. Arrays.deepToString(): 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 multidimensional 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. Arrays.toString() Arrays.deepToString() Below is illustration of Arrays.toString() and Arrays.deepToString(): 1. Single dimension array of Integer. Java // Java program to show the usage of// Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Integer[] a = { 1, 2, 3, 4, 5 }; System.out.println("Using Arrays.toString(): " + Arrays.toString(a)); System.out.println("Using Arrays.deepToString(): " + Arrays.deepToString(a)); }} Using Arrays.toString(): [1, 2, 3, 4, 5] Using Arrays.deepToString(): [1, 2, 3, 4, 5] 2. Single dimension Array of Primitive(int) in which only Arrays.toString() work. Java // Java program to show the usage of// Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println("Using Arrays.toString(): " + Arrays.toString(a)); }} Using Arrays.toString(): [1, 2, 3, 4, 5] 3. Multi-Dimension Array: Java // Java program to show the usage of // Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Integer[] a1 = { 1, 2, 3, 4, 5 }; Integer[] a2 = { 6, 7, 8, 9, 10 }; Integer[][] multi = { a1, a2 }; System.out.println("Using Arrays.toString(): " + Arrays.toString(multi)); System.out.println("Using Arrays.deepToString(): " + Arrays.deepToString(multi)); }} Using Arrays.toString(): [[Ljava.lang.Integer;@3d075dc0, [Ljava.lang.Integer;@214c265e] Using Arrays.deepToString(): [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] Java-Arrays Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Informed and Uninformed Search in AI Difference between HashMap and HashSet Difference between Internal and External fragmentation Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24467, "s": 24439, "text": "\n28 Jan, 2021" }, { "code": null, "e": 24736, "s": 24467, "text": "The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on." }, { "code": null, "e": 25048, "s": 24736, "text": "Arrays.toString(): Returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Returns “null” if a is null." }, { "code": null, "e": 25274, "s": 25048, "text": "In the case of an Object Array, if the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents." }, { "code": null, "e": 25335, "s": 25274, "text": "Parameters: The array whose string representation to return." }, { "code": null, "e": 25384, "s": 25335, "text": "Returns: The string representation of the array." }, { "code": null, "e": 25933, "s": 25384, "text": "Arrays.deepToString(): 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 multidimensional arrays to strings." }, { "code": null, "e": 25941, "s": 25933, "text": "Syntax:" }, { "code": null, "e": 25989, "s": 25941, "text": "public static String deepToString(Object[] arr)" }, { "code": null, "e": 26042, "s": 25989, "text": "arr – An array whose string representation is needed" }, { "code": null, "e": 26148, "s": 26042, "text": "This function returns string representation of arr[]. It returns “null” if the specified array is null." }, { "code": null, "e": 26166, "s": 26148, "text": "Arrays.toString()" }, { "code": null, "e": 26188, "s": 26166, "text": "Arrays.deepToString()" }, { "code": null, "e": 26258, "s": 26188, "text": "Below is illustration of Arrays.toString() and Arrays.deepToString():" }, { "code": null, "e": 26296, "s": 26258, "text": "1. Single dimension array of Integer." }, { "code": null, "e": 26301, "s": 26296, "text": "Java" }, { "code": "// Java program to show the usage of// Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Integer[] a = { 1, 2, 3, 4, 5 }; System.out.println(\"Using Arrays.toString(): \" + Arrays.toString(a)); System.out.println(\"Using Arrays.deepToString(): \" + Arrays.deepToString(a)); }}", "e": 26744, "s": 26301, "text": null }, { "code": null, "e": 26831, "s": 26744, "text": "Using Arrays.toString(): [1, 2, 3, 4, 5]\nUsing Arrays.deepToString(): [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 26913, "s": 26831, "text": "2. Single dimension Array of Primitive(int) in which only Arrays.toString() work." }, { "code": null, "e": 26918, "s": 26913, "text": "Java" }, { "code": "// Java program to show the usage of// Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5 }; System.out.println(\"Using Arrays.toString(): \" + Arrays.toString(a)); }}", "e": 27246, "s": 26918, "text": null }, { "code": null, "e": 27288, "s": 27246, "text": "Using Arrays.toString(): [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 27314, "s": 27288, "text": "3. Multi-Dimension Array:" }, { "code": null, "e": 27319, "s": 27314, "text": "Java" }, { "code": "// Java program to show the usage of // Arrays.toString() and Arrays.deepToString() import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Integer[] a1 = { 1, 2, 3, 4, 5 }; Integer[] a2 = { 6, 7, 8, 9, 10 }; Integer[][] multi = { a1, a2 }; System.out.println(\"Using Arrays.toString(): \" + Arrays.toString(multi)); System.out.println(\"Using Arrays.deepToString(): \" + Arrays.deepToString(multi)); }}", "e": 27867, "s": 27319, "text": null }, { "code": null, "e": 28021, "s": 27867, "text": "Using Arrays.toString(): [[Ljava.lang.Integer;@3d075dc0, [Ljava.lang.Integer;@214c265e]\nUsing Arrays.deepToString(): [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]\n" }, { "code": null, "e": 28033, "s": 28021, "text": "Java-Arrays" }, { "code": null, "e": 28040, "s": 28033, "text": "Picked" }, { "code": null, "e": 28064, "s": 28040, "text": "Technical Scripter 2020" }, { "code": null, "e": 28083, "s": 28064, "text": "Difference Between" }, { "code": null, "e": 28088, "s": 28083, "text": "Java" }, { "code": null, "e": 28107, "s": 28088, "text": "Technical Scripter" }, { "code": null, "e": 28112, "s": 28107, "text": "Java" }, { "code": null, "e": 28210, "s": 28112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28219, "s": 28210, "text": "Comments" }, { "code": null, "e": 28232, "s": 28219, "text": "Old Comments" }, { "code": null, "e": 28293, "s": 28232, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28361, "s": 28293, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28417, "s": 28361, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 28456, "s": 28417, "text": "Difference between HashMap and HashSet" }, { "code": null, "e": 28511, "s": 28456, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28526, "s": 28511, "text": "Arrays in Java" }, { "code": null, "e": 28570, "s": 28526, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28592, "s": 28570, "text": "For-each loop in Java" }, { "code": null, "e": 28617, "s": 28592, "text": "Reverse a string in Java" } ]
Resolve MySQL ERROR 1064 (42000): You have an error in your syntax?
This error occurs if let’s say you used var_char instead of varchar type. To remove this type of error, use, for example, varchar(100) instead of var_char(100). Let us now see how this error occurs − mysql> create table removeErrorDemo -> ( -> StudentId int, -> StudentName var_char(50) -> ); The following is the output displaying the error − ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'var_char(50) )' at line 4 Now let us remove the error. Here is the query to remove error 1064 (42000) − mysql> create table removeErrorDemo -> ( -> StudentId int, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (1.72 sec) Above, we have set varchar correctly, therefore no error will occur.
[ { "code": null, "e": 1223, "s": 1062, "text": "This error occurs if let’s say you used var_char instead of varchar type. To remove this type of error, use, for example, varchar(100) instead of var_char(100)." }, { "code": null, "e": 1262, "s": 1223, "text": "Let us now see how this error occurs −" }, { "code": null, "e": 1367, "s": 1262, "text": "mysql> create table removeErrorDemo\n -> (\n -> StudentId int,\n -> StudentName var_char(50)\n -> );" }, { "code": null, "e": 1418, "s": 1367, "text": "The following is the output displaying the error −" }, { "code": null, "e": 1599, "s": 1418, "text": "ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that\ncorresponds to your MySQL server version for the right syntax to use near 'var_char(50)\n)' at line 4" }, { "code": null, "e": 1677, "s": 1599, "text": "Now let us remove the error. Here is the query to remove error 1064 (42000) −" }, { "code": null, "e": 1819, "s": 1677, "text": "mysql> create table removeErrorDemo\n -> (\n -> StudentId int,\n -> StudentName varchar(100)\n -> );\nQuery OK, 0 rows affected (1.72 sec)" }, { "code": null, "e": 1888, "s": 1819, "text": "Above, we have set varchar correctly, therefore no error will occur." } ]
Reverse a String | Practice | GeeksforGeeks
You are given a string s. You need to reverse the string. Example 1: Input: s = Geeks Output: skeeG Example 2: Input: s = for Output: rof Your Task: You only need to complete the function reverseWord() that takes s as parameter and returns the reversed string. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1). Constraints: 1 <= |s| <= 10000 0 dnpanday90in 7 hours -------- JAVA --------class Reverse{ // Complete the function // str: input string public static String reverseWord(String str) { StringBuilder s=new StringBuilder(); String[] a=str.split(" "); for(int i=a[0].length()-1;i>=0;i--){ s.append(str.charAt(i)); } return s.toString(); }} 0 reshmisanjayanin 6 hours string reverseWord(string str){ string s=""; for(int i=str.length()-1;i>=0;i--) { s+=str[i]; } return s; //Your code here} 0 mahiagrawal121345 minutes ago def reverseWord(s): return s[::-1] s=Geeks t=reverseWord(s) print(t) 0 iamgauravshukla6 hours ago Easiest Solution and Faster also 👍 def reverseWord(s): return s[::-1] -1 nihithreddyr16 hours ago class Reverse { // Complete the function // str: input string public static String reverseWord(String str) { char[] strArray = str.toCharArray(); reverseCharacterArray(strArray,0,strArray.length-1); String reversedWord = new String(strArray); return reversedWord; } public static void reverseCharacterArray(char[] strArray,int startIndex,int endIndex){ if(startIndex >= endIndex){ return; } strArray[startIndex] ^= strArray[endIndex]; strArray[endIndex] ^= strArray[startIndex]; strArray[startIndex] ^= strArray[endIndex]; reverseCharacterArray(strArray,startIndex+1,endIndex-1); } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 284, "s": 226, "text": "You are given a string s. You need to reverse the string." }, { "code": null, "e": 295, "s": 284, "text": "Example 1:" }, { "code": null, "e": 327, "s": 295, "text": "Input:\ns = Geeks\nOutput: skeeG\n" }, { "code": null, "e": 338, "s": 327, "text": "Example 2:" }, { "code": null, "e": 365, "s": 338, "text": "Input:\ns = for\nOutput: rof" }, { "code": null, "e": 376, "s": 365, "text": "Your Task:" }, { "code": null, "e": 488, "s": 376, "text": "You only need to complete the function reverseWord() that takes s as parameter and returns the reversed string." }, { "code": null, "e": 554, "s": 488, "text": "Expected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 585, "s": 554, "text": "Constraints:\n1 <= |s| <= 10000" }, { "code": null, "e": 587, "s": 585, "text": "0" }, { "code": null, "e": 608, "s": 587, "text": "dnpanday90in 7 hours" }, { "code": null, "e": 945, "s": 608, "text": "-------- JAVA --------class Reverse{ // Complete the function // str: input string public static String reverseWord(String str) { StringBuilder s=new StringBuilder(); String[] a=str.split(\" \"); for(int i=a[0].length()-1;i>=0;i--){ s.append(str.charAt(i)); } return s.toString(); }}" }, { "code": null, "e": 947, "s": 945, "text": "0" }, { "code": null, "e": 972, "s": 947, "text": "reshmisanjayanin 6 hours" }, { "code": null, "e": 1111, "s": 972, "text": "string reverseWord(string str){ string s=\"\"; for(int i=str.length()-1;i>=0;i--) { s+=str[i]; } return s; //Your code here}" }, { "code": null, "e": 1113, "s": 1111, "text": "0" }, { "code": null, "e": 1143, "s": 1113, "text": "mahiagrawal121345 minutes ago" }, { "code": null, "e": 1163, "s": 1143, "text": "def reverseWord(s):" }, { "code": null, "e": 1182, "s": 1163, "text": " return s[::-1]" }, { "code": null, "e": 1192, "s": 1184, "text": "s=Geeks" }, { "code": null, "e": 1209, "s": 1192, "text": "t=reverseWord(s)" }, { "code": null, "e": 1218, "s": 1209, "text": "print(t)" }, { "code": null, "e": 1220, "s": 1218, "text": "0" }, { "code": null, "e": 1247, "s": 1220, "text": "iamgauravshukla6 hours ago" }, { "code": null, "e": 1282, "s": 1247, "text": "Easiest Solution and Faster also 👍" }, { "code": null, "e": 1319, "s": 1282, "text": "def reverseWord(s): return s[::-1]" }, { "code": null, "e": 1322, "s": 1319, "text": "-1" }, { "code": null, "e": 1347, "s": 1322, "text": "nihithreddyr16 hours ago" }, { "code": null, "e": 2047, "s": 1347, "text": "class Reverse\n{\n // Complete the function\n // str: input string\n public static String reverseWord(String str)\n {\n char[] strArray = str.toCharArray();\n reverseCharacterArray(strArray,0,strArray.length-1);\n String reversedWord = new String(strArray);\n return reversedWord;\n }\n public static void reverseCharacterArray(char[] strArray,int startIndex,int endIndex){\n if(startIndex >= endIndex){\n return;\n }\n strArray[startIndex] ^= strArray[endIndex];\n strArray[endIndex] ^= strArray[startIndex];\n strArray[startIndex] ^= strArray[endIndex];\n reverseCharacterArray(strArray,startIndex+1,endIndex-1);\n }\n}" }, { "code": null, "e": 2193, "s": 2047, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 2229, "s": 2193, "text": " Login to access your submissions. " }, { "code": null, "e": 2239, "s": 2229, "text": "\nProblem\n" }, { "code": null, "e": 2249, "s": 2239, "text": "\nContest\n" }, { "code": null, "e": 2312, "s": 2249, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2497, "s": 2312, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 2781, "s": 2497, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 2927, "s": 2781, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 3004, "s": 2927, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 3045, "s": 3004, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 3073, "s": 3045, "text": "Disable browser extensions." }, { "code": null, "e": 3144, "s": 3073, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 3331, "s": 3144, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Java Program to Find Reverse of a Number Using Recursion
10 Jun, 2022 Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved. To solve any problem using recursion, we should simply follow the below steps: Assume the smaller problem from the problem which is similar to the bigger/original problem.Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.Approach the solution and link the answer to the smaller problem given by recursive function to find the answer to the bigger/original problem using it. Assume the smaller problem from the problem which is similar to the bigger/original problem. Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition. Approach the solution and link the answer to the smaller problem given by recursive function to find the answer to the bigger/original problem using it. Example: Input: 14689 Output: 98641 Input: 7654321 Output: 1234567 Approach 1: In this approach, we can simply print the unit digit of a number. And then call the recursive function for the number after removing this unit digit( number/10) And this process continues till the number is reduced to a single-digit number. Example: num = 82695 reverse(82695) | |__print(5) reverse(8269) | |__print(9) reverse(826) | |__print(6) reverse(82) | |__print(2) reverse(8) | |__print(8) return Java // Java program to reverse// an integer recursivelyclass GFG { // Recursive function to print // the number in reversed form public static void Reverse(int num) { // base condition to end recursive calls if (num < 10) { System.out.println(num); return; } else { // print the unit digit of the given number System.out.print(num % 10); // calling function for remaining number other // than unit digit Reverse(num / 10); } } // driver code public static void main(String args[]) { // number to be reversed int num = 98765; System.out.print("Reversed Number: "); // calling recursive function // to print the number in // reversed form Reverse(num); }} Reversed Number: 56789 Approach 2: In this approach, we can simply maintain a variable in which we can store the number reversed till now. We can do this by extracting a unit digit from the number and then adding this extracted integer into the reversed number But the key factor here is that we have to multiply the reversed number by 10 before adding this extracted number to the reversed number. Example: num = 48291 ans = 0 -> variable to store reversed number How this works: reverse(num) | |__ temp = num % 10 -> extracting unit digit from number ans = ans*10 + temp -> adding temp at unit position in reversed number reverse(num/10) -> calling function for remaining number Implementation: reverse(48291) | |__ temp=1 ans= 0*10 + 1 --> ans=1 reverse(4829) | |__ temp=9 ans= 1*10 + 9 --> ans=19 reverse(482) | |__ temp= 2 ans= 19*10 +2 --> ans=192 reverse(48) | |__ temp=8 ans=192*10 + 8 --> ans=1928 reverse(4) | |__ temp=4 ans=1928*10 +4 --> ans=19284 reverse(0) | |__ return ans Java // Java program to reverse an integer recursivelyclass GFG { // Variable to store reversed // number after every // recursive call static int ans = 0; static int Reverse(int var) { // base condition to end the // recursive calling of function if (var == 0) { // We have reversed the // complete number and // stored in ans variable return ans; } if (var > 0) { // temp variable to store the digit at unit // place in the number int temp = var % 10; // Add this temp variable in the ans variable // which stores the number reversed till now ans = ans * 10 + temp; // recursive calling of function to reverse the // remaining number Reverse(var / 10); } // returning final answer when the number is // reversed completely return ans; } public static void main(String[] args) { // Number to be reversed int var = 98765; // Variable to store reversed number returned by // reverse function int rev; // Calling reverse function and storing the return // value in rev variable rev = Reverse(var); // Printing the Reversed Number System.out.println("Reversed number: " + rev); }} Reversed number: 56789 Note: Java does not throw an exception when an overflow occurs so a problem of overflow might occur if the reversed number is greater than Integer.MAX_VALUE (2147483647) in method 2 but there will be no such problem in method 1. adnanirshad158 vinayedula Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2022" }, { "code": null, "e": 186, "s": 52, "text": "Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved." }, { "code": null, "e": 265, "s": 186, "text": "To solve any problem using recursion, we should simply follow the below steps:" }, { "code": null, "e": 620, "s": 265, "text": "Assume the smaller problem from the problem which is similar to the bigger/original problem.Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.Approach the solution and link the answer to the smaller problem given by recursive function to find the answer to the bigger/original problem using it." }, { "code": null, "e": 713, "s": 620, "text": "Assume the smaller problem from the problem which is similar to the bigger/original problem." }, { "code": null, "e": 824, "s": 713, "text": "Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition." }, { "code": null, "e": 977, "s": 824, "text": "Approach the solution and link the answer to the smaller problem given by recursive function to find the answer to the bigger/original problem using it." }, { "code": null, "e": 986, "s": 977, "text": "Example:" }, { "code": null, "e": 1047, "s": 986, "text": "Input: 14689\nOutput: 98641\n\nInput: 7654321\nOutput: 1234567" }, { "code": null, "e": 1060, "s": 1047, "text": "Approach 1: " }, { "code": null, "e": 1126, "s": 1060, "text": "In this approach, we can simply print the unit digit of a number." }, { "code": null, "e": 1221, "s": 1126, "text": "And then call the recursive function for the number after removing this unit digit( number/10)" }, { "code": null, "e": 1302, "s": 1221, "text": "And this process continues till the number is reduced to a single-digit number. " }, { "code": null, "e": 1311, "s": 1302, "text": "Example:" }, { "code": null, "e": 1905, "s": 1311, "text": " \n num = 82695\n reverse(82695)\n |\n |__print(5)\n reverse(8269)\n |\n |__print(9)\n reverse(826)\n |\n |__print(6)\n reverse(82)\n |\n |__print(2)\n reverse(8)\n |\n |__print(8)\n return" }, { "code": null, "e": 1910, "s": 1905, "text": "Java" }, { "code": "// Java program to reverse// an integer recursivelyclass GFG { // Recursive function to print // the number in reversed form public static void Reverse(int num) { // base condition to end recursive calls if (num < 10) { System.out.println(num); return; } else { // print the unit digit of the given number System.out.print(num % 10); // calling function for remaining number other // than unit digit Reverse(num / 10); } } // driver code public static void main(String args[]) { // number to be reversed int num = 98765; System.out.print(\"Reversed Number: \"); // calling recursive function // to print the number in // reversed form Reverse(num); }}", "e": 2758, "s": 1910, "text": null }, { "code": null, "e": 2784, "s": 2761, "text": "Reversed Number: 56789" }, { "code": null, "e": 2799, "s": 2786, "text": "Approach 2: " }, { "code": null, "e": 2905, "s": 2801, "text": "In this approach, we can simply maintain a variable in which we can store the number reversed till now." }, { "code": null, "e": 3027, "s": 2905, "text": "We can do this by extracting a unit digit from the number and then adding this extracted integer into the reversed number" }, { "code": null, "e": 3166, "s": 3027, "text": "But the key factor here is that we have to multiply the reversed number by 10 before adding this extracted number to the reversed number. " }, { "code": null, "e": 3177, "s": 3168, "text": "Example:" }, { "code": null, "e": 4759, "s": 3179, "text": "num = 48291\nans = 0 -> variable to store reversed number\n \nHow this works: \n reverse(num)\n |\n |__ temp = num % 10 -> extracting unit digit from number\n ans = ans*10 + temp -> adding temp at unit position in reversed number \n reverse(num/10) -> calling function for remaining number\nImplementation:\n reverse(48291)\n |\n |__ temp=1\n ans= 0*10 + 1 --> ans=1\n reverse(4829)\n |\n |__ temp=9\n ans= 1*10 + 9 --> ans=19\n reverse(482)\n |\n |__ temp= 2\n ans= 19*10 +2 --> ans=192\n reverse(48)\n |\n |__ temp=8\n ans=192*10 + 8 --> ans=1928\n reverse(4)\n |\n |__ temp=4\n ans=1928*10 +4 --> ans=19284\n reverse(0)\n |\n |__ return ans\n " }, { "code": null, "e": 4766, "s": 4761, "text": "Java" }, { "code": "// Java program to reverse an integer recursivelyclass GFG { // Variable to store reversed // number after every // recursive call static int ans = 0; static int Reverse(int var) { // base condition to end the // recursive calling of function if (var == 0) { // We have reversed the // complete number and // stored in ans variable return ans; } if (var > 0) { // temp variable to store the digit at unit // place in the number int temp = var % 10; // Add this temp variable in the ans variable // which stores the number reversed till now ans = ans * 10 + temp; // recursive calling of function to reverse the // remaining number Reverse(var / 10); } // returning final answer when the number is // reversed completely return ans; } public static void main(String[] args) { // Number to be reversed int var = 98765; // Variable to store reversed number returned by // reverse function int rev; // Calling reverse function and storing the return // value in rev variable rev = Reverse(var); // Printing the Reversed Number System.out.println(\"Reversed number: \" + rev); }}", "e": 6167, "s": 4766, "text": null }, { "code": null, "e": 6193, "s": 6170, "text": "Reversed number: 56789" }, { "code": null, "e": 6424, "s": 6195, "text": "Note: Java does not throw an exception when an overflow occurs so a problem of overflow might occur if the reversed number is greater than Integer.MAX_VALUE (2147483647) in method 2 but there will be no such problem in method 1." }, { "code": null, "e": 6441, "s": 6426, "text": "adnanirshad158" }, { "code": null, "e": 6452, "s": 6441, "text": "vinayedula" }, { "code": null, "e": 6457, "s": 6452, "text": "Java" }, { "code": null, "e": 6471, "s": 6457, "text": "Java Programs" }, { "code": null, "e": 6476, "s": 6471, "text": "Java" }, { "code": null, "e": 6574, "s": 6476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6589, "s": 6574, "text": "Stream In Java" }, { "code": null, "e": 6610, "s": 6589, "text": "Introduction to Java" }, { "code": null, "e": 6631, "s": 6610, "text": "Constructors in Java" }, { "code": null, "e": 6650, "s": 6631, "text": "Exceptions in Java" }, { "code": null, "e": 6667, "s": 6650, "text": "Generics in Java" }, { "code": null, "e": 6693, "s": 6667, "text": "Java Programming Examples" }, { "code": null, "e": 6727, "s": 6693, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 6774, "s": 6727, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 6812, "s": 6774, "text": "Factory method design pattern in Java" } ]
SQL Server Identity
21 Mar, 2018 Identity column of a table is a column whose value increases automatically. The value in an identity column is created by the server. A user generally cannot insert a value into an identity column. Identity column can be used to uniquely identify the rows in the table. Syntax: IDENTITY [( seed, increment)] Seed: Starting value of a column. Default value is 1. Increment: Incremental value that is added to the identity value of the previous row that was loaded. The default value 1. The ‘ID’ column of the table starts from 1 as the seed value provided is 1 and is incremented by 1 at each row. The ‘ID’ column of the table starts from 1 but is incremented by 2 as the increment value is passed as 2 while creating the ‘IDENTITY’ Column. SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Mar, 2018" }, { "code": null, "e": 323, "s": 53, "text": "Identity column of a table is a column whose value increases automatically. The value in an identity column is created by the server. A user generally cannot insert a value into an identity column. Identity column can be used to uniquely identify the rows in the table." }, { "code": null, "e": 331, "s": 323, "text": "Syntax:" }, { "code": null, "e": 551, "s": 331, "text": "IDENTITY [( seed, increment)]\n\n\nSeed: Starting value of a column. \n Default value is 1.\n\nIncrement: Incremental value that is \nadded to the identity value of the previous \nrow that was loaded. The default value 1.\n" }, { "code": null, "e": 663, "s": 551, "text": "The ‘ID’ column of the table starts from 1 as the seed value provided is 1 and is incremented by 1 at each row." }, { "code": null, "e": 806, "s": 663, "text": "The ‘ID’ column of the table starts from 1 but is incremented by 2 as the increment value is passed as 2 while creating the ‘IDENTITY’ Column." }, { "code": null, "e": 817, "s": 806, "text": "SQL-Server" }, { "code": null, "e": 821, "s": 817, "text": "SQL" }, { "code": null, "e": 825, "s": 821, "text": "SQL" } ]
Turing Machine as Comparator
23 Aug, 2021 Prerequisite – Turing Machine Problem : Draw a turing machine which compare two numbers. Using unary format to represent the number. For example, 4 is represented by 4 = 1 1 1 1 or 0 0 0 0 Lets use one’s for representation. Example: Approach: Comparing two numbers by comparing number of ‘1’s.Comparing ‘1’s by marking them ‘X’.If ‘1’s are remaining in left of ‘0’, then first number is greater.If ‘1’s are remaining in right of ‘0’, then second number is greater.If both ‘1’ are finished then both numbers are equal. Comparing two numbers by comparing number of ‘1’s. Comparing ‘1’s by marking them ‘X’. If ‘1’s are remaining in left of ‘0’, then first number is greater. If ‘1’s are remaining in right of ‘0’, then second number is greater. If both ‘1’ are finished then both numbers are equal. Steps: Step-1: Convert 1 into X and move right and goto step 2. If symbol is 0 ignore it and move right and goto step-6. Step-2: Keep ignoring 1 and move towards right. Ignore 0 move right and goto step-3. Step-3: Keep ignoring X and move towards right. Ignore 1 move left and goto step-4. If B is found ignore it and move left and goto step-9. Step-4: Keep ignoring X and move towards left. Ignore 0 move left and goto step-5. Step-5: Keep ignoring 1 and move towards left. Ignore X move right and goto step-1. Step-6: Keep ignoring X and move towards right. If B is found ignore it and move left and goto step-8. If 1 is found ignore it and move right and goto step-7. Step-7: Stop the Machine (A < B) Step-8: Stop the Machine (A > B) Step-9: Stop the Machine (A = B) State transition diagram : Comparator for A < B Comparator for A = B Comparator for A > B Universal Comparator for A < B, A = B, A > B Here, Q0 shows the initial state and Q2, Q3, Q4, Q5 shows the transition state and (A < B), (A = B)and (A > B) shows the final state. 0, 1 are the variables used and R, L shows right and left. Explanation: Using Q0, when 1 is found make it X and go to leftand to state Q1. and if 0 found move to right to Q5 state. On the state Q1, ignore all 1 and goto right.If 0 found ignore it and goto right into next state Q2. In Q2, ignore all X and move right.If B found stop the execution and you will goto the state showing A > B, If 1 found make it X move left and to Q3. In Q3 state, ignore all X and move left.If 0 found ignore it move left to Q4. In Q4, ignore all 1 and move left.If X found ignore it move right. In Q5 state, ignore all X and move right.If 1 found ignore it move right and stop the machine it will give the result that A < B.And if, B found move left to stop the machine it will give the result that A = B anikaseth98 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2021" }, { "code": null, "e": 82, "s": 52, "text": "Prerequisite – Turing Machine" }, { "code": null, "e": 220, "s": 82, "text": "Problem : Draw a turing machine which compare two numbers. Using unary format to represent the number. For example, 4 is represented by " }, { "code": null, "e": 245, "s": 220, "text": "4 = 1 1 1 1 or 0 0 0 0 " }, { "code": null, "e": 281, "s": 245, "text": "Lets use one’s for representation. " }, { "code": null, "e": 291, "s": 281, "text": "Example: " }, { "code": null, "e": 305, "s": 293, "text": "Approach: " }, { "code": null, "e": 580, "s": 305, "text": "Comparing two numbers by comparing number of ‘1’s.Comparing ‘1’s by marking them ‘X’.If ‘1’s are remaining in left of ‘0’, then first number is greater.If ‘1’s are remaining in right of ‘0’, then second number is greater.If both ‘1’ are finished then both numbers are equal." }, { "code": null, "e": 631, "s": 580, "text": "Comparing two numbers by comparing number of ‘1’s." }, { "code": null, "e": 667, "s": 631, "text": "Comparing ‘1’s by marking them ‘X’." }, { "code": null, "e": 735, "s": 667, "text": "If ‘1’s are remaining in left of ‘0’, then first number is greater." }, { "code": null, "e": 805, "s": 735, "text": "If ‘1’s are remaining in right of ‘0’, then second number is greater." }, { "code": null, "e": 859, "s": 805, "text": "If both ‘1’ are finished then both numbers are equal." }, { "code": null, "e": 868, "s": 859, "text": "Steps: " }, { "code": null, "e": 984, "s": 868, "text": "Step-1: Convert 1 into X and move right and goto step 2. If symbol is 0 ignore it and move right and goto step-6. " }, { "code": null, "e": 1069, "s": 984, "text": "Step-2: Keep ignoring 1 and move towards right. Ignore 0 move right and goto step-3." }, { "code": null, "e": 1208, "s": 1069, "text": "Step-3: Keep ignoring X and move towards right. Ignore 1 move left and goto step-4. If B is found ignore it and move left and goto step-9." }, { "code": null, "e": 1291, "s": 1208, "text": "Step-4: Keep ignoring X and move towards left. Ignore 0 move left and goto step-5." }, { "code": null, "e": 1375, "s": 1291, "text": "Step-5: Keep ignoring 1 and move towards left. Ignore X move right and goto step-1." }, { "code": null, "e": 1534, "s": 1375, "text": "Step-6: Keep ignoring X and move towards right. If B is found ignore it and move left and goto step-8. If 1 is found ignore it and move right and goto step-7." }, { "code": null, "e": 1567, "s": 1534, "text": "Step-7: Stop the Machine (A < B)" }, { "code": null, "e": 1600, "s": 1567, "text": "Step-8: Stop the Machine (A > B)" }, { "code": null, "e": 1633, "s": 1600, "text": "Step-9: Stop the Machine (A = B)" }, { "code": null, "e": 1662, "s": 1633, "text": "State transition diagram : " }, { "code": null, "e": 1683, "s": 1662, "text": "Comparator for A < B" }, { "code": null, "e": 1704, "s": 1683, "text": "Comparator for A = B" }, { "code": null, "e": 1725, "s": 1704, "text": "Comparator for A > B" }, { "code": null, "e": 1772, "s": 1725, "text": "Universal Comparator for A < B, A = B, A > B " }, { "code": null, "e": 1966, "s": 1772, "text": "Here, Q0 shows the initial state and Q2, Q3, Q4, Q5 shows the transition state and (A < B), (A = B)and (A > B) shows the final state. 0, 1 are the variables used and R, L shows right and left. " }, { "code": null, "e": 1981, "s": 1966, "text": "Explanation: " }, { "code": null, "e": 2090, "s": 1981, "text": "Using Q0, when 1 is found make it X and go to leftand to state Q1. and if 0 found move to right to Q5 state." }, { "code": null, "e": 2191, "s": 2090, "text": "On the state Q1, ignore all 1 and goto right.If 0 found ignore it and goto right into next state Q2." }, { "code": null, "e": 2341, "s": 2191, "text": "In Q2, ignore all X and move right.If B found stop the execution and you will goto the state showing A > B, If 1 found make it X move left and to Q3." }, { "code": null, "e": 2419, "s": 2341, "text": "In Q3 state, ignore all X and move left.If 0 found ignore it move left to Q4." }, { "code": null, "e": 2486, "s": 2419, "text": "In Q4, ignore all 1 and move left.If X found ignore it move right." }, { "code": null, "e": 2696, "s": 2486, "text": "In Q5 state, ignore all X and move right.If 1 found ignore it move right and stop the machine it will give the result that A < B.And if, B found move left to stop the machine it will give the result that A = B" }, { "code": null, "e": 2710, "s": 2698, "text": "anikaseth98" }, { "code": null, "e": 2718, "s": 2710, "text": "GATE CS" }, { "code": null, "e": 2751, "s": 2718, "text": "Theory of Computation & Automata" } ]
File.WriteAllLines(String, IEnumerable<String>) Method in C# with Examples
01 Jun, 2020 File.WriteAllLines(String, IEnumerable<String>) is an inbuilt File class method that is used to create a new file, writes a collection of strings to the file, and then closes the file. Syntax: public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String>contents); Parameter: This function accepts two parameters which are illustrated below: path: This is the specified file where collection of strings are going to be written. contents: This is the specified lines to write to the file. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method. ArgumentNullException: Either path or contents are null. DirectoryNotFoundException: The path is invalid. IOException: An I/O error occurred while opening the file. PathTooLongException: The path exceeds the system-defined maximum length. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission. Below are the programs to illustrate the File.WriteAllLines(String, IEnumerable) method. Program 1: Before running the below code, a file file.txt is created whose contents are going to be filtered that are shown below- Below code, itself creates a new file gfg.txt which contains the filtered strings. // C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>) method // Using System, System.IO// and System.Linq namespacesusing System;using System.IO;using System.Linq; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @"file.txt"; static void Main(string[] args) { // Reading content of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with "G" where(line.StartsWith("G")) select line; // Creating a new file gfg.txt with the // filtered contents File.WriteAllLines(@"gfg.txt", da); Console.WriteLine("Writing the filtered collection "+ "of strings to the file has been done."); }} Output: Writing the filtered collection of strings to the file has been done. After running the above code, the above output is shown, and a new file gfg.txt is created shown below- Program 2: Before running the below code, two files file.txt and gfg.txt are created with some contents shown below- Below code overwrites the file gfg.txt with the selected contents of the file file.txt. // C# program to illustrate the usage// of File.WriteAllLines(String,// IEnumerable<String>) method // Using System, System.IO// and System.Linq namespacesusing System;using System.IO;using System.Linq; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @"file.txt"; static void Main(string[] args) { // Reading the contents of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with "g" where(line.StartsWith("g")) select line; // Overwriting the file gfg.txt with the // selected string of the file file.txt File.WriteAllLines(@"gfg.txt", da); Console.WriteLine("Overwriting the selected collection"+ " of strings to the file has been done."); }} Output: Overwriting the selected collection of strings to the file has been done. After running the above code, the above output is shown, and the file gfg.txt contents became like shown below: CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2020" }, { "code": null, "e": 213, "s": 28, "text": "File.WriteAllLines(String, IEnumerable<String>) is an inbuilt File class method that is used to create a new file, writes a collection of strings to the file, and then closes the file." }, { "code": null, "e": 221, "s": 213, "text": "Syntax:" }, { "code": null, "e": 325, "s": 221, "text": "public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String>contents);" }, { "code": null, "e": 402, "s": 325, "text": "Parameter: This function accepts two parameters which are illustrated below:" }, { "code": null, "e": 488, "s": 402, "text": "path: This is the specified file where collection of strings are going to be written." }, { "code": null, "e": 548, "s": 488, "text": "contents: This is the specified lines to write to the file." }, { "code": null, "e": 560, "s": 548, "text": "Exceptions:" }, { "code": null, "e": 719, "s": 560, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method." }, { "code": null, "e": 776, "s": 719, "text": "ArgumentNullException: Either path or contents are null." }, { "code": null, "e": 825, "s": 776, "text": "DirectoryNotFoundException: The path is invalid." }, { "code": null, "e": 884, "s": 825, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 958, "s": 884, "text": "PathTooLongException: The path exceeds the system-defined maximum length." }, { "code": null, "e": 1015, "s": 958, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 1084, "s": 1015, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 1344, "s": 1084, "text": "UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission." }, { "code": null, "e": 1433, "s": 1344, "text": "Below are the programs to illustrate the File.WriteAllLines(String, IEnumerable) method." }, { "code": null, "e": 1564, "s": 1433, "text": "Program 1: Before running the below code, a file file.txt is created whose contents are going to be filtered that are shown below-" }, { "code": null, "e": 1647, "s": 1564, "text": "Below code, itself creates a new file gfg.txt which contains the filtered strings." }, { "code": "// C# program to illustrate the usage// of File.WriteAllLines(String, // IEnumerable<String>) method // Using System, System.IO// and System.Linq namespacesusing System;using System.IO;using System.Linq; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @\"file.txt\"; static void Main(string[] args) { // Reading content of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with \"G\" where(line.StartsWith(\"G\")) select line; // Creating a new file gfg.txt with the // filtered contents File.WriteAllLines(@\"gfg.txt\", da); Console.WriteLine(\"Writing the filtered collection \"+ \"of strings to the file has been done.\"); }}", "e": 2492, "s": 1647, "text": null }, { "code": null, "e": 2500, "s": 2492, "text": "Output:" }, { "code": null, "e": 2571, "s": 2500, "text": "Writing the filtered collection of strings to the file has been done.\n" }, { "code": null, "e": 2675, "s": 2571, "text": "After running the above code, the above output is shown, and a new file gfg.txt is created shown below-" }, { "code": null, "e": 2792, "s": 2675, "text": "Program 2: Before running the below code, two files file.txt and gfg.txt are created with some contents shown below-" }, { "code": null, "e": 2880, "s": 2792, "text": "Below code overwrites the file gfg.txt with the selected contents of the file file.txt." }, { "code": "// C# program to illustrate the usage// of File.WriteAllLines(String,// IEnumerable<String>) method // Using System, System.IO// and System.Linq namespacesusing System;using System.IO;using System.Linq; class GFG { // Specifying a file from where // some contents are going to be filtered static string Path = @\"file.txt\"; static void Main(string[] args) { // Reading the contents of file.txt var da = from line in File.ReadLines(Path) // Selecting lines started with \"g\" where(line.StartsWith(\"g\")) select line; // Overwriting the file gfg.txt with the // selected string of the file file.txt File.WriteAllLines(@\"gfg.txt\", da); Console.WriteLine(\"Overwriting the selected collection\"+ \" of strings to the file has been done.\"); }}", "e": 3754, "s": 2880, "text": null }, { "code": null, "e": 3762, "s": 3754, "text": "Output:" }, { "code": null, "e": 3837, "s": 3762, "text": "Overwriting the selected collection of strings to the file has been done.\n" }, { "code": null, "e": 3949, "s": 3837, "text": "After running the above code, the above output is shown, and the file gfg.txt contents became like shown below:" }, { "code": null, "e": 3970, "s": 3949, "text": "CSharp-File-Handling" }, { "code": null, "e": 3973, "s": 3970, "text": "C#" } ]
Scala List concatenation with example
29 Jul, 2019 In order to concatenate two lists we need to utilize concat() method in Scala.Syntax: List.concat(l1, l2) In above syntax, l1 is list1 and l2 is list2.Below is the example to concat two lists in scala.Example #1: // Scala program of concat()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating two lists val m1 = List(1, 2, 3) val m2 = List(4, 5, 6) // Applying concat method val res = List.concat(m1, m2) // Displays output println(res) }} List(1, 2, 3, 4, 5, 6) Example #2: // Scala program of concat()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating two lists val m1 = List(1, 2, 3) val m2 = List(3, 4, 5) // Applying concat method val res = List.concat(m1, m2) // Displays output println(res) }} List(1, 2, 3, 3, 4, 5) Here, the identical elements are not removed. Scala Scala-list Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2019" }, { "code": null, "e": 114, "s": 28, "text": "In order to concatenate two lists we need to utilize concat() method in Scala.Syntax:" }, { "code": null, "e": 134, "s": 114, "text": "List.concat(l1, l2)" }, { "code": null, "e": 241, "s": 134, "text": "In above syntax, l1 is list1 and l2 is list2.Below is the example to concat two lists in scala.Example #1:" }, { "code": "// Scala program of concat()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating two lists val m1 = List(1, 2, 3) val m2 = List(4, 5, 6) // Applying concat method val res = List.concat(m1, m2) // Displays output println(res) }}", "e": 611, "s": 241, "text": null }, { "code": null, "e": 635, "s": 611, "text": "List(1, 2, 3, 4, 5, 6)\n" }, { "code": null, "e": 647, "s": 635, "text": "Example #2:" }, { "code": "// Scala program of concat()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating two lists val m1 = List(1, 2, 3) val m2 = List(3, 4, 5) // Applying concat method val res = List.concat(m1, m2) // Displays output println(res) }}", "e": 1017, "s": 647, "text": null }, { "code": null, "e": 1041, "s": 1017, "text": "List(1, 2, 3, 3, 4, 5)\n" }, { "code": null, "e": 1087, "s": 1041, "text": "Here, the identical elements are not removed." }, { "code": null, "e": 1093, "s": 1087, "text": "Scala" }, { "code": null, "e": 1104, "s": 1093, "text": "Scala-list" }, { "code": null, "e": 1117, "s": 1104, "text": "Scala-Method" }, { "code": null, "e": 1123, "s": 1117, "text": "Scala" } ]
HTML | Window alert( ) Method
26 Jul, 2019 The Window alert() method is used to display an alert box. It displays a specified message along with an OK button and is generally used to make sure that the information comes through the user.It returns a string which represents the text to display in the alert box. Syntax: alert(message) Below program illustrates the Window alert() Method : Displaying an alert box. <!DOCTYPE html><html> <head> <title> Window alert() Method in HTML </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Window alert() Method</h2> <p> For displaying the alert message, double click the "Show Alert Message" button: </p> <button ondblclick="myalert()"> Show Alert Message </button> <script> function myalert() { alert("Welcome to GeeksforGeeks.\n " + "It is the best portal for computer" + "science enthusiasts!"); } </script> </body> </html> Output: After clicking the button Supported Browsers: The browser supported by Window alert( ) Method are listed below: Google Chrome Internet Explorer Firefox Opera Safari HTML-Methods HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 297, "s": 28, "text": "The Window alert() method is used to display an alert box. It displays a specified message along with an OK button and is generally used to make sure that the information comes through the user.It returns a string which represents the text to display in the alert box." }, { "code": null, "e": 305, "s": 297, "text": "Syntax:" }, { "code": null, "e": 320, "s": 305, "text": "alert(message)" }, { "code": null, "e": 374, "s": 320, "text": "Below program illustrates the Window alert() Method :" }, { "code": null, "e": 399, "s": 374, "text": "Displaying an alert box." }, { "code": "<!DOCTYPE html><html> <head> <title> Window alert() Method in HTML </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Window alert() Method</h2> <p> For displaying the alert message, double click the \"Show Alert Message\" button: </p> <button ondblclick=\"myalert()\"> Show Alert Message </button> <script> function myalert() { alert(\"Welcome to GeeksforGeeks.\\n \" + \"It is the best portal for computer\" + \"science enthusiasts!\"); } </script> </body> </html>", "e": 1178, "s": 399, "text": null }, { "code": null, "e": 1186, "s": 1178, "text": "Output:" }, { "code": null, "e": 1212, "s": 1186, "text": "After clicking the button" }, { "code": null, "e": 1298, "s": 1212, "text": "Supported Browsers: The browser supported by Window alert( ) Method are listed below:" }, { "code": null, "e": 1312, "s": 1298, "text": "Google Chrome" }, { "code": null, "e": 1330, "s": 1312, "text": "Internet Explorer" }, { "code": null, "e": 1338, "s": 1330, "text": "Firefox" }, { "code": null, "e": 1344, "s": 1338, "text": "Opera" }, { "code": null, "e": 1351, "s": 1344, "text": "Safari" }, { "code": null, "e": 1364, "s": 1351, "text": "HTML-Methods" }, { "code": null, "e": 1369, "s": 1364, "text": "HTML" }, { "code": null, "e": 1386, "s": 1369, "text": "Web Technologies" }, { "code": null, "e": 1391, "s": 1386, "text": "HTML" } ]
Python Counter to find the size of largest subset of anagram words
27 Dec, 2017 Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan gnamate Output: 3 Explanation Anagram strings(1) - ant, tan Anagram strings(2) - magenta, magnate, gnamate Thus, only second subset have largest size i.e., 3 Input: cars bikes arcs steer Output: 2 We have existing solution for this problem please refer Find the size of largest subset of anagram words link. We can solve this problem quickly in python using Counter() method. Approach is very simple, Split input string separated by space into words.As we know two strings are anagram to each other if they contain same character set. So to get all those strings together first we will sort each string in given list of strings.Now create a dictionary using Counter method having strings as keys and their frequencies as value.Check for maximum value of frequencies, that will be the largest sub-set of anagram strings. Split input string separated by space into words. As we know two strings are anagram to each other if they contain same character set. So to get all those strings together first we will sort each string in given list of strings. Now create a dictionary using Counter method having strings as keys and their frequencies as value. Check for maximum value of frequencies, that will be the largest sub-set of anagram strings. # Function to find the size of largest subset # of anagram wordsfrom collections import Counter def maxAnagramSize(input): # split input string separated by space input = input.split(" ") # sort each string in given list of strings for i in range(0,len(input)): input[i]=''.join(sorted(input[i])) # now create dictionary using counter method # which will have strings as key and their # frequencies as value freqDict = Counter(input) # get maximum value of frequency print (max(freqDict.values())) # Driver programif __name__ == "__main__": input = 'ant magenta magnate tan gnamate' maxAnagramSize(input) Output: 3 anagram Python anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2017" }, { "code": null, "e": 364, "s": 54, "text": "Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other." }, { "code": null, "e": 374, "s": 364, "text": "Examples:" }, { "code": null, "e": 628, "s": 374, "text": "Input: \nant magenta magnate tan gnamate\nOutput: 3\nExplanation\nAnagram strings(1) - ant, tan\nAnagram strings(2) - magenta, magnate,\n gnamate\nThus, only second subset have largest\nsize i.e., 3\n\nInput: \ncars bikes arcs steer \nOutput: 2\n" }, { "code": null, "e": 832, "s": 628, "text": "We have existing solution for this problem please refer Find the size of largest subset of anagram words link. We can solve this problem quickly in python using Counter() method. Approach is very simple," }, { "code": null, "e": 1251, "s": 832, "text": "Split input string separated by space into words.As we know two strings are anagram to each other if they contain same character set. So to get all those strings together first we will sort each string in given list of strings.Now create a dictionary using Counter method having strings as keys and their frequencies as value.Check for maximum value of frequencies, that will be the largest sub-set of anagram strings." }, { "code": null, "e": 1301, "s": 1251, "text": "Split input string separated by space into words." }, { "code": null, "e": 1480, "s": 1301, "text": "As we know two strings are anagram to each other if they contain same character set. So to get all those strings together first we will sort each string in given list of strings." }, { "code": null, "e": 1580, "s": 1480, "text": "Now create a dictionary using Counter method having strings as keys and their frequencies as value." }, { "code": null, "e": 1673, "s": 1580, "text": "Check for maximum value of frequencies, that will be the largest sub-set of anagram strings." }, { "code": "# Function to find the size of largest subset # of anagram wordsfrom collections import Counter def maxAnagramSize(input): # split input string separated by space input = input.split(\" \") # sort each string in given list of strings for i in range(0,len(input)): input[i]=''.join(sorted(input[i])) # now create dictionary using counter method # which will have strings as key and their # frequencies as value freqDict = Counter(input) # get maximum value of frequency print (max(freqDict.values())) # Driver programif __name__ == \"__main__\": input = 'ant magenta magnate tan gnamate' maxAnagramSize(input)", "e": 2333, "s": 1673, "text": null }, { "code": null, "e": 2341, "s": 2333, "text": "Output:" }, { "code": null, "e": 2344, "s": 2341, "text": "3\n" }, { "code": null, "e": 2352, "s": 2344, "text": "anagram" }, { "code": null, "e": 2359, "s": 2352, "text": "Python" }, { "code": null, "e": 2367, "s": 2359, "text": "anagram" } ]
Implementation of Affine Cipher
07 Jul, 2022 The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. The whole process relies on working modulo m (the length of the alphabet used). In the affine cipher, the letters of an alphabet of size m are first mapped to the integers in the range 0 ... m-1. The ‘key’ for the Affine cipher consists of 2 numbers, we’ll call them a and b. The following discussion assumes the use of a 26 character alphabet (m = 26). a should be chosen to be relatively prime to m (i.e. a should have no factors in common with m). Encryption It uses modular arithmetic to transform the integer that each plaintext letter corresponds to into another integer that correspond to a ciphertext letter. The encryption function for a single letter is E ( x ) = ( a x + b ) mod m modulus m: size of the alphabet a and b: key of the cipher. a must be chosen such that a and m are coprime. Decryption In deciphering the ciphertext, we must perform the opposite (or inverse) functions on the ciphertext to retrieve the plaintext. Once again, the first step is to convert each of the ciphertext letters into their integer values. The decryption function is D ( x ) = a^-1 ( x - b ) mod m a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation 1 = a a^-1 mod m . To find a multiplicative inverse We need to find a number x such that: If we find the number x such that the equation is true, then x is the inverse of a, and we call it a^-1. The easiest way to solve this equation is to search each of the numbers 1 to 25, and see which one satisfies the equation. [g,x,d] = gcd(a,m); % we can ignore g and d, we dont need them x = mod(x,m); If you now multiply x and a and reduce the result (mod 26), you will get the answer 1. Remember, this is just the definition of an inverse i.e. if a*x = 1 (mod 26), then x is an inverse of a (and a is an inverse of x) Example: Implementation: C++ Java Python C# //CPP program to illustrate Affine Cipher #include<bits/stdc++.h>using namespace std; //Key values of a and bconst int a = 17;const int b = 20; string encryptMessage(string msg){ ///Cipher Text initially empty string cipher = ""; for (int i = 0; i < msg.length(); i++) { // Avoid space to be encrypted if(msg[i]!=' ') /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ cipher = cipher + (char) ((((a * (msg[i]-'A') ) + b) % 26) + 'A'); else //else simply append space character cipher += msg[i]; } return cipher;} string decryptCipher(string cipher){ string msg = ""; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; //Check if (a*i)%26 == 1, //then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.length(); i++) { if(cipher[i]!=' ') /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ msg = msg + (char) (((a_inv * ((cipher[i]+'A' - b)) % 26)) + 'A'); else //else simply append space character msg += cipher[i]; } return msg;} //Driver Programint main(void){ string msg = "AFFINE CIPHER"; //Calling encryption function string cipherText = encryptMessage(msg); cout << "Encrypted Message is : " << cipherText<<endl; //Calling Decryption function cout << "Decrypted Message is: " << decryptCipher(cipherText); return 0;} // Java program to illustrate Affine Cipher class GFG{ // Key values of a and b static int a = 17; static int b = 20; static String encryptMessage(char[] msg) { /// Cipher Text initially empty String cipher = ""; for (int i = 0; i < msg.length; i++) { // Avoid space to be encrypted /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else // else simply append space character { cipher += msg[i]; } } return cipher; } static String decryptCipher(String cipher) { String msg = ""; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; // Check if (a*i)%26 == 1, // then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.length(); i++) { /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher.charAt(i) != ' ') { msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); } else //else simply append space character { msg += cipher.charAt(i); } } return msg; } // Driver code public static void main(String[] args) { String msg = "AFFINE CIPHER"; // Calling encryption function String cipherText = encryptMessage(msg.toCharArray()); System.out.println("Encrypted Message is : " + cipherText); // Calling Decryption function System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); }} // This code contributed by Rajput-Ji # Implementation of Affine Cipher in Python # Extended Euclidean Algorithm for finding modular inverse# eg: modinv(7, 26) = 15def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m): gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse does not exist else: return x % m # affine cipher encryption function# returns the cipher textdef affine_encrypt(text, key): ''' C = (a*P + b) % 26 ''' return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26) + ord('A')) for t in text.upper().replace(' ', '') ]) # affine cipher decryption function# returns original textdef affine_decrypt(cipher, key): ''' P = (a^-1 * (C - b)) % 26 ''' return ''.join([ chr((( modinv(key[0], 26)*(ord(c) - ord('A') - key[1])) % 26) + ord('A')) for c in cipher ]) # Driver Code to test the above functionsdef main(): # declaring text and key text = 'AFFINE CIPHER' key = [17, 20] # calling encryption function affine_encrypted_text = affine_encrypt(text, key) print('Encrypted Text: {}'.format( affine_encrypted_text )) # calling decryption function print('Decrypted Text: {}'.format ( affine_decrypt(affine_encrypted_text, key) )) if __name__ == '__main__': main()# This code is contributed by# Bhushan Borole // C# program to illustrate Affine Cipherusing System; class GFG{ // Key values of a and b static int a = 17; static int b = 20; static String encryptMessage(char[] msg) { /// Cipher Text initially empty String cipher = ""; for (int i = 0; i < msg.Length; i++) { // Avoid space to be encrypted /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else // else simply append space character { cipher += msg[i]; } } return cipher; } static String decryptCipher(String cipher) { String msg = ""; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; // Check if (a*i)%26 == 1, // then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.Length; i++) { /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher[i] != ' ') { msg = msg + (char) (((a_inv * ((cipher[i] + 'A' - b)) % 26)) + 'A'); } else //else simply append space character { msg += cipher[i]; } } return msg; } // Driver code public static void Main(String[] args) { String msg = "AFFINE CIPHER"; // Calling encryption function String cipherText = encryptMessage(msg.ToCharArray()); Console.WriteLine("Encrypted Message is : " + cipherText); // Calling Decryption function Console.WriteLine("Decrypted Message is: " + decryptCipher(cipherText)); }} /* This code contributed by PrinciRaj1992 */ Encrypted Message is : UBBAHK CAPJKX Decrypted Message is: AFFINE CIPHER This article is contributed by Yasin Zafar. 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. BhushanBorole Rajput-Ji princiraj1992 surinderdawra388 simmytarika5 surindertarika1234 hardikkoriintern cryptography Strings Strings cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 671, "s": 54, "text": "The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. The whole process relies on working modulo m (the length of the alphabet used). In the affine cipher, the letters of an alphabet of size m are first mapped to the integers in the range 0 ... m-1. " }, { "code": null, "e": 927, "s": 671, "text": "The ‘key’ for the Affine cipher consists of 2 numbers, we’ll call them a and b. The following discussion assumes the use of a 26 character alphabet (m = 26). a should be chosen to be relatively prime to m (i.e. a should have no factors in common with m). " }, { "code": null, "e": 938, "s": 927, "text": "Encryption" }, { "code": null, "e": 1142, "s": 938, "text": "It uses modular arithmetic to transform the integer that each plaintext letter corresponds to into another integer that correspond to a ciphertext letter. The encryption function for a single letter is " }, { "code": null, "e": 1280, "s": 1142, "text": " E ( x ) = ( a x + b ) mod m \nmodulus m: size of the alphabet\na and b: key of the cipher.\na must be chosen such that a and m are coprime." }, { "code": null, "e": 1291, "s": 1280, "text": "Decryption" }, { "code": null, "e": 1547, "s": 1291, "text": "In deciphering the ciphertext, we must perform the opposite (or inverse) functions on the ciphertext to retrieve the plaintext. Once again, the first step is to convert each of the ciphertext letters into their integer values. The decryption function is " }, { "code": null, "e": 1682, "s": 1547, "text": "D ( x ) = a^-1 ( x - b ) mod m\na^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation\n1 = a a^-1 mod m ." }, { "code": null, "e": 1716, "s": 1682, "text": "To find a multiplicative inverse " }, { "code": null, "e": 1983, "s": 1716, "text": "We need to find a number x such that: If we find the number x such that the equation is true, then x is the inverse of a, and we call it a^-1. The easiest way to solve this equation is to search each of the numbers 1 to 25, and see which one satisfies the equation. " }, { "code": null, "e": 2069, "s": 1983, "text": "[g,x,d] = gcd(a,m); % we can ignore g and d, we dont need them\nx = mod(x,m); " }, { "code": null, "e": 2287, "s": 2069, "text": "If you now multiply x and a and reduce the result (mod 26), you will get the answer 1. Remember, this is just the definition of an inverse i.e. if a*x = 1 (mod 26), then x is an inverse of a (and a is an inverse of x)" }, { "code": null, "e": 2297, "s": 2287, "text": "Example: " }, { "code": null, "e": 2313, "s": 2297, "text": "Implementation:" }, { "code": null, "e": 2317, "s": 2313, "text": "C++" }, { "code": null, "e": 2322, "s": 2317, "text": "Java" }, { "code": null, "e": 2329, "s": 2322, "text": "Python" }, { "code": null, "e": 2332, "s": 2329, "text": "C#" }, { "code": "//CPP program to illustrate Affine Cipher #include<bits/stdc++.h>using namespace std; //Key values of a and bconst int a = 17;const int b = 20; string encryptMessage(string msg){ ///Cipher Text initially empty string cipher = \"\"; for (int i = 0; i < msg.length(); i++) { // Avoid space to be encrypted if(msg[i]!=' ') /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ cipher = cipher + (char) ((((a * (msg[i]-'A') ) + b) % 26) + 'A'); else //else simply append space character cipher += msg[i]; } return cipher;} string decryptCipher(string cipher){ string msg = \"\"; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; //Check if (a*i)%26 == 1, //then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.length(); i++) { if(cipher[i]!=' ') /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ msg = msg + (char) (((a_inv * ((cipher[i]+'A' - b)) % 26)) + 'A'); else //else simply append space character msg += cipher[i]; } return msg;} //Driver Programint main(void){ string msg = \"AFFINE CIPHER\"; //Calling encryption function string cipherText = encryptMessage(msg); cout << \"Encrypted Message is : \" << cipherText<<endl; //Calling Decryption function cout << \"Decrypted Message is: \" << decryptCipher(cipherText); return 0;}", "e": 4306, "s": 2332, "text": null }, { "code": "// Java program to illustrate Affine Cipher class GFG{ // Key values of a and b static int a = 17; static int b = 20; static String encryptMessage(char[] msg) { /// Cipher Text initially empty String cipher = \"\"; for (int i = 0; i < msg.length; i++) { // Avoid space to be encrypted /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else // else simply append space character { cipher += msg[i]; } } return cipher; } static String decryptCipher(String cipher) { String msg = \"\"; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; // Check if (a*i)%26 == 1, // then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.length(); i++) { /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher.charAt(i) != ' ') { msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); } else //else simply append space character { msg += cipher.charAt(i); } } return msg; } // Driver code public static void main(String[] args) { String msg = \"AFFINE CIPHER\"; // Calling encryption function String cipherText = encryptMessage(msg.toCharArray()); System.out.println(\"Encrypted Message is : \" + cipherText); // Calling Decryption function System.out.println(\"Decrypted Message is: \" + decryptCipher(cipherText)); }} // This code contributed by Rajput-Ji", "e": 6626, "s": 4306, "text": null }, { "code": "# Implementation of Affine Cipher in Python # Extended Euclidean Algorithm for finding modular inverse# eg: modinv(7, 26) = 15def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m): gcd, x, y = egcd(a, m) if gcd != 1: return None # modular inverse does not exist else: return x % m # affine cipher encryption function# returns the cipher textdef affine_encrypt(text, key): ''' C = (a*P + b) % 26 ''' return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26) + ord('A')) for t in text.upper().replace(' ', '') ]) # affine cipher decryption function# returns original textdef affine_decrypt(cipher, key): ''' P = (a^-1 * (C - b)) % 26 ''' return ''.join([ chr((( modinv(key[0], 26)*(ord(c) - ord('A') - key[1])) % 26) + ord('A')) for c in cipher ]) # Driver Code to test the above functionsdef main(): # declaring text and key text = 'AFFINE CIPHER' key = [17, 20] # calling encryption function affine_encrypted_text = affine_encrypt(text, key) print('Encrypted Text: {}'.format( affine_encrypted_text )) # calling decryption function print('Decrypted Text: {}'.format ( affine_decrypt(affine_encrypted_text, key) )) if __name__ == '__main__': main()# This code is contributed by# Bhushan Borole", "e": 8088, "s": 6626, "text": null }, { "code": "// C# program to illustrate Affine Cipherusing System; class GFG{ // Key values of a and b static int a = 17; static int b = 20; static String encryptMessage(char[] msg) { /// Cipher Text initially empty String cipher = \"\"; for (int i = 0; i < msg.Length; i++) { // Avoid space to be encrypted /* applying encryption formula ( a x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else // else simply append space character { cipher += msg[i]; } } return cipher; } static String decryptCipher(String cipher) { String msg = \"\"; int a_inv = 0; int flag = 0; //Find a^-1 (the multiplicative inverse of a //in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; // Check if (a*i)%26 == 1, // then i will be the multiplicative inverse of a if (flag == 1) { a_inv = i; } } for (int i = 0; i < cipher.Length; i++) { /*Applying decryption formula a^-1 ( x - b ) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher[i] != ' ') { msg = msg + (char) (((a_inv * ((cipher[i] + 'A' - b)) % 26)) + 'A'); } else //else simply append space character { msg += cipher[i]; } } return msg; } // Driver code public static void Main(String[] args) { String msg = \"AFFINE CIPHER\"; // Calling encryption function String cipherText = encryptMessage(msg.ToCharArray()); Console.WriteLine(\"Encrypted Message is : \" + cipherText); // Calling Decryption function Console.WriteLine(\"Decrypted Message is: \" + decryptCipher(cipherText)); }} /* This code contributed by PrinciRaj1992 */", "e": 10405, "s": 8088, "text": null }, { "code": null, "e": 10478, "s": 10405, "text": "Encrypted Message is : UBBAHK CAPJKX\nDecrypted Message is: AFFINE CIPHER" }, { "code": null, "e": 10774, "s": 10478, "text": "This article is contributed by Yasin Zafar. 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": 10788, "s": 10774, "text": "BhushanBorole" }, { "code": null, "e": 10798, "s": 10788, "text": "Rajput-Ji" }, { "code": null, "e": 10812, "s": 10798, "text": "princiraj1992" }, { "code": null, "e": 10829, "s": 10812, "text": "surinderdawra388" }, { "code": null, "e": 10842, "s": 10829, "text": "simmytarika5" }, { "code": null, "e": 10861, "s": 10842, "text": "surindertarika1234" }, { "code": null, "e": 10878, "s": 10861, "text": "hardikkoriintern" }, { "code": null, "e": 10891, "s": 10878, "text": "cryptography" }, { "code": null, "e": 10899, "s": 10891, "text": "Strings" }, { "code": null, "e": 10907, "s": 10899, "text": "Strings" }, { "code": null, "e": 10920, "s": 10907, "text": "cryptography" } ]
Materialize CSS Icons
16 May, 2022 Materialize CSS provides a rich set of material icons of google which can be downloaded from Material Design specs. Icon libraries that are supported by materialize css are Google Material Icons, Font Awesome Icons and Bootstrap Icons. Different icons can be selected from Material Icons. Library and Usage: To use these icon, the following line is added in the <head> part of the HTML code. <link href=”https://fonts.googleapis.com/icon?family=Material+Icons” rel=”stylesheet”> Then to use the icons, name of the icon is provided in the <i> part of HTML element. <i class="material-icons">add</i> Material icon sizes: Materialize CSS provides icons in four sizes: tiny, small, medium, large. The sizes for tiny, small, medium and large are 1 rem, 2 rem, 4 rem and 6 rem respectively. <i class = "material-icons tiny">add</i> <i class = "material-icons small">add</i> <i class = "material-icons">add</i> <i class = "material-icons medium">add</i> <i class = "material-icons large">add</i> Example: HTML <!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <div class="card-panel"> <h3 class="green-text">Icons</h3> <div class="container"> <div class="row"> <div class="col"> <i class="material-icons tiny">account_circle</i> </div> <div class="col"> <i class="material-icons"> account_circle</i> </div> <div class="col"> <i class="material-icons small">account_circle</i> </div> <div class="col"> <i class="material-icons medium">account_circle</i> </div> <div class="col"> <i class="material-icons large">account_circle</i> </div> </div> </div> </div> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html> Output: Materialize-CSS CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2022" }, { "code": null, "e": 317, "s": 28, "text": "Materialize CSS provides a rich set of material icons of google which can be downloaded from Material Design specs. Icon libraries that are supported by materialize css are Google Material Icons, Font Awesome Icons and Bootstrap Icons. Different icons can be selected from Material Icons." }, { "code": null, "e": 420, "s": 317, "text": "Library and Usage: To use these icon, the following line is added in the <head> part of the HTML code." }, { "code": null, "e": 507, "s": 420, "text": "<link href=”https://fonts.googleapis.com/icon?family=Material+Icons” rel=”stylesheet”>" }, { "code": null, "e": 592, "s": 507, "text": "Then to use the icons, name of the icon is provided in the <i> part of HTML element." }, { "code": null, "e": 626, "s": 592, "text": "<i class=\"material-icons\">add</i>" }, { "code": null, "e": 814, "s": 626, "text": "Material icon sizes: Materialize CSS provides icons in four sizes: tiny, small, medium, large. The sizes for tiny, small, medium and large are 1 rem, 2 rem, 4 rem and 6 rem respectively." }, { "code": null, "e": 1026, "s": 814, "text": "<i class = \"material-icons tiny\">add</i> \n<i class = \"material-icons small\">add</i> \n<i class = \"material-icons\">add</i> \n<i class = \"material-icons medium\">add</i> \n<i class = \"material-icons large\">add</i>" }, { "code": null, "e": 1036, "s": 1026, "text": "Example: " }, { "code": null, "e": 1041, "s": 1036, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Google Icon Font--> <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\"> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script> <!--Let browser know website is optimized for mobile--> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <div class=\"card-panel\"> <h3 class=\"green-text\">Icons</h3> <div class=\"container\"> <div class=\"row\"> <div class=\"col\"> <i class=\"material-icons tiny\">account_circle</i> </div> <div class=\"col\"> <i class=\"material-icons\"> account_circle</i> </div> <div class=\"col\"> <i class=\"material-icons small\">account_circle</i> </div> <div class=\"col\"> <i class=\"material-icons medium\">account_circle</i> </div> <div class=\"col\"> <i class=\"material-icons large\">account_circle</i> </div> </div> </div> </div> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>", "e": 2708, "s": 1041, "text": null }, { "code": null, "e": 2716, "s": 2708, "text": "Output:" }, { "code": null, "e": 2732, "s": 2716, "text": "Materialize-CSS" }, { "code": null, "e": 2736, "s": 2732, "text": "CSS" }, { "code": null, "e": 2741, "s": 2736, "text": "HTML" }, { "code": null, "e": 2758, "s": 2741, "text": "Web Technologies" }, { "code": null, "e": 2763, "s": 2758, "text": "HTML" } ]
How to convert unstructured data to structured data using Python ?
21 Apr, 2022 Prerequisite: What is Unstructured Data? Sometimes machine generates data in an unstructured way which is less interpretable. For example, Biometric Data, where an employee does Punch – IN or OUT several times with mistakes. We can not analyze the data and identify the mistakes unless it’s in a tabular form. In this article, we will take unstructured biometric data and convert it into useful information in terms of a table. Here we will work with Daily Punch – In Report. Data is given below. Punch records captured for Main Door and Second Door. Main Door is Outdoor Gate and Second Door is Project Room Gate. We need to identify which employee spent how much time in the project room or second door. The dataset we’re going to use is Bio.xlsx: Here is the Biometric Data for John Sherrif where punch in and punch out records has given for Main Door and Second Door. 08:33:in(Second Door),08:35:(Second Door),08:37:(Main Door),09:04:out(Second Door),09:09:in(Second Door), 09:15:out(Second Door),09:15:(Second Door),09:18:(Second Door),09:52:in(Second Door),09:54:(Second Door), 10:00:out(Main Door),10:17:in(Main Door),10:53:out(Second Door),11:47:in(Second Door),11:47:(Second Door), 11:49:(Second Door),11:50:(Second Door),13:08:out(Second Door),13:09:(Second Door),13:12:(Second Door), 13:14:in(Second Door),13:36:out(Second Door),13:36:(Second Door),14:27:in(Second Door),14:32:out(Main Door), 14:48:in(Second Door),14:48:(Second Door),14:49:(Second Door),14:52:(Main Door),14:56:out(Second Door), 14:57:(Second Door),14:59:(Second Door),15:04:in(Second Door),16:22:out(Second Door),16:34:in(Second Door), 19:58:out(Main Door), The above Data is not insightful to analyze. Our desired output is: Understanding the Data: John Sherrif did Punch – IN at 08:33 for the first time and Punch – OUT at 09:04 for the first time. John did Punch – IN at 14:27 but forgot to do Punch – OUT. The ‘in’ signifies he/she forgot to do Punch IN and ‘out’ signifies vice versa. Data Cleaning & Creating a table for status, Punch Code, and Emp Code. Python3 import pandas as pd # load datadf = pd.read_excel('bio.xlsx') # removing NA values from the# dataframe dfdf = df.fillna("") # removing all the blank rowsdf1 = df.dropna(how='all') # picking the rows where present# or absent values are there from# 14 no columndf1 = df1[df1['Unnamed: 14'].str.contains('sent')] # Extracting only the Employee# Namesdf_name = df.dropna(how='all') # from column no 3 we are picking# Employee namesdf_name = df_name[df_name['Unnamed: 3'].str.contains('Employee')] # creating a new dataframe for Status,# Punch Records and Employee CodeszippedList = list( zip(df1['Unnamed: 14'], df1['Unnamed: 15'], df_name['Unnamed: 7'])) abc = pd.DataFrame(zippedList)abc.head() Output: Extracting Data for Second Door only. Python3 # Splitting the values by comma in 1# no column (punch records)for i in range(len(abc)): abc[1][i] = abc[1][i].split(",") second_door = [] for i in range(len(abc)): s_d = [] # Extracting all the values which contains # only :in(Second Door) or :out(Second Dorr) for j in range(len(abc[1][i])): if ':in(Second Door)' in abc[1][i][j]: s_d.append(abc[1][i][j]) if 'out(Second Door)' in abc[1][i][j]: s_d.append(abc[1][i][j]) second_door.append(s_d)(second_door[0]) Output: The punch record should start with ‘IN’ and end with ‘OUT’. Creating the pattern if it doesn’t follow. Python3 # Punch Records should start with# the keyword 'in'. If it doesn't# follow then we will add 'in' and it# significants that the employee forgot# to do punch inin_time = []for i in range(len(second_door)): try: if ':in(Second Door)' not in second_door[i][0]: second_door[i].insert(0, 'in') except: pass # Punch Records should end with the keyword# 'out'. If it doesn't follow then we will# add 'out' and it significants that the# employee forgot to do punch outout_time = []for i in range(len(second_door)): try: if ':out(Second Door)' not in second_door[i][(len(second_door[i]))-1]: second_door[i].insert(((len(second_door[i]))), 'out') except: passsecond_door[0] Output: Creating the pattern ‘IN – OUT – IN – .....- OUT’. If someone forgot to do Punch – IN then we will put ‘IN’ & if someone forgot to do Punch – OUT then we will put ‘OUT’. Python3 # final_in contains PUNCH - IN# records for all employeesfinal_in = [] # final_out contains PUNCH - OUT# records for all employeesfinal_out = [] for k in range(len(second_door)): in_gate = [] out_gate = [] # even position should be for Punch- # IN and odd position should be for # Punch - OUT if it doesn't follow # then we will create the pattern by # putting 'in' or 'out' for i in range(len(second_door[k])): if i % 2 == 0 and 'in' in second_door[k][i]: in_gate.append(second_door[k][i]) try: if 'out' not in second_door[k][i+1]: out_gate.append('out') except: pass if i % 2 != 0 and 'out' in second_door[k][i]: out_gate.append(second_door[k][i]) try: if 'in' not in second_door[k][i+1]: in_gate.append('in') except: pass if i % 2 != 0 and 'in' in second_door[k][i]: in_gate.append(second_door[k][i]) try: if 'out' not in second_door[k][i+1]: out_gate.append('out') except: pass if i % 2 == 0 and 'out' in second_door[k][i]: out_gate.append(second_door[k][i]) try: if 'in' not in second_door[k][i+1]: in_gate.append('in') except: pass final_in.append(in_gate) final_out.append(out_gate) # final_in or final_out keep the# records as a list under list form.# to solve the problem we will merge the list # aa contains merged list of Punch - INaa = final_in[0]for i in range(len(final_in)-1): aa = aa + final_in[i+1] # bb contains merged list of Punch - OUTbb = final_out[0]for i in range(len(final_out)-1): bb = bb + final_out[i+1] for i in range(len(final_in[0])): print(final_in[0][i], ' ', final_out[0][i]) Output: Creating the final table. Python # Creating a dataframe called df_finaldf_final = []df_final = pd.DataFrame(df_final) # Merging the Employee NamesName = []for i in range(len(abc)): for j in range(len(final_in[i])): Name.append(abc[2][i])df_final['Name'] = Name # Zipping the Employee Name, Punch -IN# records and Punch - OUT recordszippedList2 = list(zip(df_final['Name'], aa, bb))abc2 = pd.DataFrame(zippedList2) # Renaming the dataframeabc2.columns = ['Emp Code', 'Punch - IN', 'Punch - OUT']abc2.to_excel('output.xlsx', index=False) # Print the tabledisplay(abc2) Output: Hence, the raw biometric data has been structured and is converted to useful information. anikaseth98 simmytarika5 Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2022" }, { "code": null, "e": 69, "s": 28, "text": "Prerequisite: What is Unstructured Data?" }, { "code": null, "e": 456, "s": 69, "text": "Sometimes machine generates data in an unstructured way which is less interpretable. For example, Biometric Data, where an employee does Punch – IN or OUT several times with mistakes. We can not analyze the data and identify the mistakes unless it’s in a tabular form. In this article, we will take unstructured biometric data and convert it into useful information in terms of a table." }, { "code": null, "e": 778, "s": 456, "text": "Here we will work with Daily Punch – In Report. Data is given below. Punch records captured for Main Door and Second Door. Main Door is Outdoor Gate and Second Door is Project Room Gate. We need to identify which employee spent how much time in the project room or second door. The dataset we’re going to use is Bio.xlsx:" }, { "code": null, "e": 901, "s": 778, "text": " Here is the Biometric Data for John Sherrif where punch in and punch out records has given for Main Door and Second Door." }, { "code": null, "e": 1007, "s": 901, "text": "08:33:in(Second Door),08:35:(Second Door),08:37:(Main Door),09:04:out(Second Door),09:09:in(Second Door)," }, { "code": null, "e": 1113, "s": 1007, "text": "09:15:out(Second Door),09:15:(Second Door),09:18:(Second Door),09:52:in(Second Door),09:54:(Second Door)," }, { "code": null, "e": 1220, "s": 1113, "text": "10:00:out(Main Door),10:17:in(Main Door),10:53:out(Second Door),11:47:in(Second Door),11:47:(Second Door)," }, { "code": null, "e": 1324, "s": 1220, "text": "11:49:(Second Door),11:50:(Second Door),13:08:out(Second Door),13:09:(Second Door),13:12:(Second Door)," }, { "code": null, "e": 1433, "s": 1324, "text": "13:14:in(Second Door),13:36:out(Second Door),13:36:(Second Door),14:27:in(Second Door),14:32:out(Main Door)," }, { "code": null, "e": 1537, "s": 1433, "text": "14:48:in(Second Door),14:48:(Second Door),14:49:(Second Door),14:52:(Main Door),14:56:out(Second Door)," }, { "code": null, "e": 1645, "s": 1537, "text": "14:57:(Second Door),14:59:(Second Door),15:04:in(Second Door),16:22:out(Second Door),16:34:in(Second Door)," }, { "code": null, "e": 1669, "s": 1645, "text": "19:58:out(Main Door), " }, { "code": null, "e": 1737, "s": 1669, "text": "The above Data is not insightful to analyze. Our desired output is:" }, { "code": null, "e": 2001, "s": 1737, "text": "Understanding the Data: John Sherrif did Punch – IN at 08:33 for the first time and Punch – OUT at 09:04 for the first time. John did Punch – IN at 14:27 but forgot to do Punch – OUT. The ‘in’ signifies he/she forgot to do Punch IN and ‘out’ signifies vice versa." }, { "code": null, "e": 2072, "s": 2001, "text": "Data Cleaning & Creating a table for status, Punch Code, and Emp Code." }, { "code": null, "e": 2080, "s": 2072, "text": "Python3" }, { "code": "import pandas as pd # load datadf = pd.read_excel('bio.xlsx') # removing NA values from the# dataframe dfdf = df.fillna(\"\") # removing all the blank rowsdf1 = df.dropna(how='all') # picking the rows where present# or absent values are there from# 14 no columndf1 = df1[df1['Unnamed: 14'].str.contains('sent')] # Extracting only the Employee# Namesdf_name = df.dropna(how='all') # from column no 3 we are picking# Employee namesdf_name = df_name[df_name['Unnamed: 3'].str.contains('Employee')] # creating a new dataframe for Status,# Punch Records and Employee CodeszippedList = list( zip(df1['Unnamed: 14'], df1['Unnamed: 15'], df_name['Unnamed: 7'])) abc = pd.DataFrame(zippedList)abc.head()", "e": 2776, "s": 2080, "text": null }, { "code": null, "e": 2787, "s": 2779, "text": "Output:" }, { "code": null, "e": 2827, "s": 2789, "text": "Extracting Data for Second Door only." }, { "code": null, "e": 2837, "s": 2829, "text": "Python3" }, { "code": "# Splitting the values by comma in 1# no column (punch records)for i in range(len(abc)): abc[1][i] = abc[1][i].split(\",\") second_door = [] for i in range(len(abc)): s_d = [] # Extracting all the values which contains # only :in(Second Door) or :out(Second Dorr) for j in range(len(abc[1][i])): if ':in(Second Door)' in abc[1][i][j]: s_d.append(abc[1][i][j]) if 'out(Second Door)' in abc[1][i][j]: s_d.append(abc[1][i][j]) second_door.append(s_d)(second_door[0])", "e": 3360, "s": 2837, "text": null }, { "code": null, "e": 3368, "s": 3360, "text": "Output:" }, { "code": null, "e": 3471, "s": 3368, "text": "The punch record should start with ‘IN’ and end with ‘OUT’. Creating the pattern if it doesn’t follow." }, { "code": null, "e": 3479, "s": 3471, "text": "Python3" }, { "code": "# Punch Records should start with# the keyword 'in'. If it doesn't# follow then we will add 'in' and it# significants that the employee forgot# to do punch inin_time = []for i in range(len(second_door)): try: if ':in(Second Door)' not in second_door[i][0]: second_door[i].insert(0, 'in') except: pass # Punch Records should end with the keyword# 'out'. If it doesn't follow then we will# add 'out' and it significants that the# employee forgot to do punch outout_time = []for i in range(len(second_door)): try: if ':out(Second Door)' not in second_door[i][(len(second_door[i]))-1]: second_door[i].insert(((len(second_door[i]))), 'out') except: passsecond_door[0]", "e": 4213, "s": 3479, "text": null }, { "code": null, "e": 4221, "s": 4213, "text": "Output:" }, { "code": null, "e": 4391, "s": 4221, "text": "Creating the pattern ‘IN – OUT – IN – .....- OUT’. If someone forgot to do Punch – IN then we will put ‘IN’ & if someone forgot to do Punch – OUT then we will put ‘OUT’." }, { "code": null, "e": 4399, "s": 4391, "text": "Python3" }, { "code": "# final_in contains PUNCH - IN# records for all employeesfinal_in = [] # final_out contains PUNCH - OUT# records for all employeesfinal_out = [] for k in range(len(second_door)): in_gate = [] out_gate = [] # even position should be for Punch- # IN and odd position should be for # Punch - OUT if it doesn't follow # then we will create the pattern by # putting 'in' or 'out' for i in range(len(second_door[k])): if i % 2 == 0 and 'in' in second_door[k][i]: in_gate.append(second_door[k][i]) try: if 'out' not in second_door[k][i+1]: out_gate.append('out') except: pass if i % 2 != 0 and 'out' in second_door[k][i]: out_gate.append(second_door[k][i]) try: if 'in' not in second_door[k][i+1]: in_gate.append('in') except: pass if i % 2 != 0 and 'in' in second_door[k][i]: in_gate.append(second_door[k][i]) try: if 'out' not in second_door[k][i+1]: out_gate.append('out') except: pass if i % 2 == 0 and 'out' in second_door[k][i]: out_gate.append(second_door[k][i]) try: if 'in' not in second_door[k][i+1]: in_gate.append('in') except: pass final_in.append(in_gate) final_out.append(out_gate) # final_in or final_out keep the# records as a list under list form.# to solve the problem we will merge the list # aa contains merged list of Punch - INaa = final_in[0]for i in range(len(final_in)-1): aa = aa + final_in[i+1] # bb contains merged list of Punch - OUTbb = final_out[0]for i in range(len(final_out)-1): bb = bb + final_out[i+1] for i in range(len(final_in[0])): print(final_in[0][i], ' ', final_out[0][i])", "e": 6318, "s": 4399, "text": null }, { "code": null, "e": 6326, "s": 6318, "text": "Output:" }, { "code": null, "e": 6352, "s": 6326, "text": "Creating the final table." }, { "code": null, "e": 6359, "s": 6352, "text": "Python" }, { "code": "# Creating a dataframe called df_finaldf_final = []df_final = pd.DataFrame(df_final) # Merging the Employee NamesName = []for i in range(len(abc)): for j in range(len(final_in[i])): Name.append(abc[2][i])df_final['Name'] = Name # Zipping the Employee Name, Punch -IN# records and Punch - OUT recordszippedList2 = list(zip(df_final['Name'], aa, bb))abc2 = pd.DataFrame(zippedList2) # Renaming the dataframeabc2.columns = ['Emp Code', 'Punch - IN', 'Punch - OUT']abc2.to_excel('output.xlsx', index=False) # Print the tabledisplay(abc2)", "e": 6903, "s": 6359, "text": null }, { "code": null, "e": 6911, "s": 6903, "text": "Output:" }, { "code": null, "e": 7001, "s": 6911, "text": "Hence, the raw biometric data has been structured and is converted to useful information." }, { "code": null, "e": 7013, "s": 7001, "text": "anikaseth98" }, { "code": null, "e": 7026, "s": 7013, "text": "simmytarika5" }, { "code": null, "e": 7040, "s": 7026, "text": "Python-pandas" }, { "code": null, "e": 7047, "s": 7040, "text": "Python" } ]
equals() on String and StringBuffer objects in Java
08 Jul, 2021 Consider the following codes in java: Java // This program prints falseclass GFG { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer("GFG"); StringBuffer sb2 = new StringBuffer("GFG"); System.out.println(sb1.equals(sb2)); }} false Java // This program prints trueclass GFG { public static void main(String[] args) { String s1 = "GFG"; String s2 = "GFG"; System.out.println(s1.equals(s2)); }} true The output is false for the first example and true for the second example. In second example, parameter to equals() belongs String class, while in first example it to StringBuffer class. When an object of String is passed, the strings are compared. But when object of StringBuffer is passed references are compared because StringBuffer does not override equals method of Object class.For example, following first program prints false and second prints true. Java // This program prints falseclass GFG { public static void main(String[] args) { String s1 = "GFG"; StringBuffer sb1 = new StringBuffer("GFG"); System.out.println(s1.equals(sb1)); }} false Java // This program prints trueclass GFG { public static void main(String[] args) { String s1 = "GFG"; StringBuffer sb1 = new StringBuffer("GFG"); String s2 = sb1.toString(); System.out.println(s1.equals(s2)); }} true pp944850 Java-String-Programs java-StringBuffer Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2021" }, { "code": null, "e": 93, "s": 53, "text": "Consider the following codes in java: " }, { "code": null, "e": 98, "s": 93, "text": "Java" }, { "code": "// This program prints falseclass GFG { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer(\"GFG\"); StringBuffer sb2 = new StringBuffer(\"GFG\"); System.out.println(sb1.equals(sb2)); }}", "e": 319, "s": 98, "text": null }, { "code": null, "e": 325, "s": 319, "text": "false" }, { "code": null, "e": 332, "s": 327, "text": "Java" }, { "code": "// This program prints trueclass GFG { public static void main(String[] args) { String s1 = \"GFG\"; String s2 = \"GFG\"; System.out.println(s1.equals(s2)); }}", "e": 500, "s": 332, "text": null }, { "code": null, "e": 505, "s": 500, "text": "true" }, { "code": null, "e": 966, "s": 507, "text": "The output is false for the first example and true for the second example. In second example, parameter to equals() belongs String class, while in first example it to StringBuffer class. When an object of String is passed, the strings are compared. But when object of StringBuffer is passed references are compared because StringBuffer does not override equals method of Object class.For example, following first program prints false and second prints true. " }, { "code": null, "e": 971, "s": 966, "text": "Java" }, { "code": "// This program prints falseclass GFG { public static void main(String[] args) { String s1 = \"GFG\"; StringBuffer sb1 = new StringBuffer(\"GFG\"); System.out.println(s1.equals(sb1)); }}", "e": 1166, "s": 971, "text": null }, { "code": null, "e": 1172, "s": 1166, "text": "false" }, { "code": null, "e": 1179, "s": 1174, "text": "Java" }, { "code": "// This program prints trueclass GFG { public static void main(String[] args) { String s1 = \"GFG\"; StringBuffer sb1 = new StringBuffer(\"GFG\"); String s2 = sb1.toString(); System.out.println(s1.equals(s2)); }}", "e": 1403, "s": 1179, "text": null }, { "code": null, "e": 1408, "s": 1403, "text": "true" }, { "code": null, "e": 1419, "s": 1410, "text": "pp944850" }, { "code": null, "e": 1440, "s": 1419, "text": "Java-String-Programs" }, { "code": null, "e": 1458, "s": 1440, "text": "java-StringBuffer" }, { "code": null, "e": 1471, "s": 1458, "text": "Java-Strings" }, { "code": null, "e": 1476, "s": 1471, "text": "Java" }, { "code": null, "e": 1489, "s": 1476, "text": "Java-Strings" }, { "code": null, "e": 1494, "s": 1489, "text": "Java" } ]
Batch Script - Quick Guide
Batch Script is incorporated to automate command sequences which are repetitive in nature. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. In most organizations, Batch Script is incorporated in some way or the other to automate stuff. Some of the features of Batch Script are − Can read inputs from users so that it can be processed further. Can read inputs from users so that it can be processed further. Has control structures such as for, if, while, switch for better automating and scripting. Has control structures such as for, if, while, switch for better automating and scripting. Supports advanced features such as Functions and Arrays. Supports advanced features such as Functions and Arrays. Supports regular expressions. Supports regular expressions. Can include other programming codes such as Perl. Can include other programming codes such as Perl. Some of the common uses of Batch Script are − Setting up servers for different purposes. Setting up servers for different purposes. Automating housekeeping activities such as deleting unwanted files or log files. Automating housekeeping activities such as deleting unwanted files or log files. Automating the deployment of applications from one environment to another. Automating the deployment of applications from one environment to another. Installing programs on various machines at once. Installing programs on various machines at once. Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe. Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file's path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR This chapter explains the environment related to Batch Script. Typically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment. Following are the different ways to launch cmd.exe − Method 1 − Go to C:\Windows\System32 and double click on the cmd file. Method 2 − Via the run command – The following snapshot shows to find the command prompt(cmd.exe) on Windows server 2012. Once the cmd.exe is launched, you will be presented with the following screen. This will be your environment for executing your batch scripts. In order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the batch file is stored in the location C:\Application\bin, you would need to follow these instructions for the PATH variable inclusion. In this chapter, we will look at some of the frequently used batch commands. This batch command shows the version of MS-DOS you are using. This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association. This batch command helps in making changes to a different directory, or displays the current directory. This batch command clears the screen. This batch command is used for copying files from one location to the other. This batch command deletes files and not directories. This batch command lists the contents of a directory. This batch command help to find the system date. This batch command displays messages, or turns command echoing on or off. This batch command exits the DOS console. This batch command creates a new directory in the current location. This batch command moves files or directories between directories. This batch command displays or sets the path variable. This batch command prompts the user and waits for a line of input to be entered. This batch command can be used to change or reset the cmd.exe prompt. This batch command removes directories, but the directories need to be empty before they can be removed. Renames files and directories This batch command is used for remarks in batch files, preventing the content of the remark from being executed. This batch command starts a program in new window, or opens a document. This batch command sets or displays the time. This batch command prints the content of a file or files to the output. This batch command displays the volume labels. Displays or sets the attributes of the files in the curret directory This batch command checks the disk for any problems. This batch command provides a list of options to the user. This batch command invokes another instance of command prompt. This batch command compares 2 files based on the file size. This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system. This batch command shows all installed device drivers and their properties. This batch command extracts files from compressed .cab cabinet files. This batch command searches for a string in files or input, outputting matching lines. This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk. This batch command shows the list of Windows-supplied commands. This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection. This batch command adds, sets or removes a disk label. This batch command displays the contents of a file or files, one screen at a time. Provides various network services, depending on the command used. This batch command sends ICMP/IP "echo" packets over the network to the designated address. This batch command shuts down a computer, or logs off the current user. This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console. This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment. This batch command shows configuration of a computer and its operating system. This batch command ends one or more tasks. This batch command lists tasks, including task name and process id (PID). This batch command copies files and directories in a more advanced way. This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth. This batch command lists the actual differences between two files. This batch command shows and configures the properties of disk partitions. This batch command sets the title displayed in the console window. Displays the list of environment variables on the current system. In this chapter, we will learn how to create, save, execute, and modify batch files. Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files − Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts. Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts. Don’t name them after common batch files which are available in the system such as ping.cmd. Don’t name them after common batch files which are available in the system such as ping.cmd. The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind. Remember to put the .bat or .cmd at the end of the file name. Choose the “Save as type” option as “All Files”. Put the entire file name in quotes “”. Following are the steps to execute a batch file − Step 1 − Open the command prompt (cmd.exe). Step 1 − Open the command prompt (cmd.exe). Step 2 − Go to the location where the .bat or .cmd file is stored. Step 2 − Go to the location where the .bat or .cmd file is stored. Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file. Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file. Following are the steps for modifying an existing batch file. Step 1 − Open windows explorer. Step 1 − Open windows explorer. Step 2 − Go to the location where the .bat or .cmd file is stored. Step 2 − Go to the location where the .bat or .cmd file is stored. Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing. Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing. Normally, the first line in a batch file often consists of the following command. @echo off By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well. Very often batch files also contains lines that start with the "Rem" command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments. Let’s construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as “List.cmd”. The code does the following − Uses the echo off command to ensure that the commands are not shown when the code is executed. Uses the echo off command to ensure that the commands are not shown when the code is executed. The Rem command is used to add a comment to say what exactly this batch file does. The Rem command is used to add a comment to say what exactly this batch file does. The dir command is used to take the contents of the location C:\Program Files. The dir command is used to take the contents of the location C:\Program Files. The ‘>’ command is used to redirect the output to the file C:\lists.txt. The ‘>’ command is used to redirect the output to the file C:\lists.txt. Finally, the echo command is used to tell the user that the operation is completed. Finally, the echo command is used to tell the user that the operation is completed. @echo off Rem This is for listing down all the files in the directory Program files dir "C:\Program Files" > C:\lists.txt echo "The program has completed" When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message “The program has completed” will be displayed. There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command. Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen. @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. 1 2 3 If we were to run the batch as Example 1 2 3 4 The output would still remain the same as above. However, the fourth parameter would be ignored. The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command. set /A variable-name=value where, variable-name is the name of the variable you want to set. variable-name is the name of the variable you want to set. value is the value which needs to be set against the variable. value is the value which needs to be set against the variable. /A – This switch is used if the value needs to be numeric in nature. /A – This switch is used if the value needs to be numeric in nature. The following example shows a simple way the set command can be used. @echo off set message=Hello World echo %message% In the above code snippet, a variable called message is defined and set with the value of "Hello World". In the above code snippet, a variable called message is defined and set with the value of "Hello World". To display the value of the variable, note that the variable needs to be enclosed in the % sign. To display the value of the variable, note that the variable needs to be enclosed in the % sign. The above command produces the following output. Hello World In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are first setting the value of 2 variables, a and b to 5 and 10 respectively. We are adding those values and storing in the variable c. We are adding those values and storing in the variable c. Finally, we are displaying the value of the variable c. Finally, we are displaying the value of the variable c. The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50 In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script. @echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program. The ‘globalvar’ is defined with a global scope and is available throughout the entire script. The ‘globalvar’ is defined with a global scope and is available throughout the entire script. The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed. The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed. The above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist. If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. @echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre It’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does. For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does. ECHO OFF IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax SETLOCAL SET WSS= IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A ENDLOCAL GOTO:EOF ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed There are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement. Rem Remarks where ‘Remarks’ is the comments which needs to be added. The following example shows a simple way the Rem command can be used. @echo off Rem This program just displays Hello World set message=Hello World echo %message% The above command produces the following output. You will notice that the line with the Rem statement will not be executed. Hello World The other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement. :: Remarks where ‘Remarks’ is the comment which needs to be added. The following example shows a simple way the Rem command can be used. @echo off :: This program just displays Hello World set message = Hello World echo %message% The above command produces the following output. You will notice that the line with the :: statement will not be executed. Hello World Note − If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed. Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it. ::=============================================================== :: The below example is used to find computer and logged on users :: ::=============================================================== ECHO OFF :: Windows version check IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL :: Command line parameter check IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax :: Keep variable local SETLOCAL :: Initialize variable SET WSS= :: Parse command line parameter IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A :: Use NET VIEW and NBTSTAT to find computers and logged on users FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A :: Done ENDLOCAL GOTO:EOF :Syntax ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable. In DOS, a string is an ordered collection of characters, such as "Hello, World!". A string can be created in DOS in the following way. Empty String String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation. In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string. A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished. This used to align text to the right, which is normally used to improve readability of number columns. This is used to extract characters from the beginning of a string. This is used to extract a substring via the position of the characters in the string. The string substitution feature can also be used to remove a substring from another string. This is used to remove the first and the last character of a string. This is used to remove all spaces in a string via substitution. To replace a substring with another string use the string substitution feature. This is used to extract characters from the end of a string. Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script. Each element of the array needs to be defined with the set command. The ‘for’ loop would be required to iterate through the values of the array. An array is created by using the following set command. set a[0]=1 Where 0 is the index of the array and 1 is the value assigned to the first element of the array. Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented. @echo off set list = 1 2 3 4 (for %%a in (%list%) do ( echo %%a )) The above command produces the following output. 1 2 3 4 You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array. @echo off set a[0]=1 echo %a[0]% In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays − @echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]% The above command produces the following output. The first element of the array is 1 The second element of the array is 2 The third element of the array is 3 To add an element to the end of the array, you can use the set element along with the last index of the array element. @echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 Rem Adding an element at the end of an array Set a[3] = 4 echo The last element of the array is %a[3]% The above command produces the following output. The last element of the array is 4 You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example − @echo off set a[0] = 1 set a[1] = 2 set a[2] = 3 Rem Setting the new value for the second element of the array Set a[1] = 5 echo The new value of the second element of the array is %a[1]% The above command produces the following output. The new value of the second element of the array is 5 Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented. @echo off setlocal enabledelayedexpansion set topic[0] = comments set topic[1] = variables set topic[2] = Arrays set topic[3] = Decision making set topic[4] = Time and date set topic[5] = Operators for /l %%n in (0,1,5) do ( echo !topic[%%n]! ) Following things need to be noted about the above program − Each element of the array needs to be specifically defined using the set command. Each element of the array needs to be specifically defined using the set command. The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array. The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array. The above command produces the following output. Comments variables Arrays Decision making Time and date Operators The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array. @echo off set Arr[0] = 1 set Arr[1] = 2 set Arr[2] = 3 set Arr[3] = 4 set "x = 0" :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a "x+=1" GOTO :SymLoop ) echo "The length of the array is" %x% Output The above command produces the following output. The length of the array is 4 Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved. @echo off set len = 3 set obj[0].Name = Joe set obj[0].ID = 1 set obj[1].Name = Mark set obj[1].ID = 2 set obj[2].Name = Mohan set obj[2].ID = 3 set i = 0 :loop if %i% equ %len% goto :eof set cur.Name= set cur.ID= for /f "usebackq delims==.tokens=1-3" %%j in (`set obj[%i%]`) do ( set cur.%%k=%%l ) echo Name = %cur.Name% echo Value = %cur.ID% set /a i = %i%+1 goto loop The following key things need to be noted about the above code. Each variable defined using the set command has 2 values associated with each index of the array. Each variable defined using the set command has 2 values associated with each index of the array. The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3. The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3. We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code. We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code. We are able to access each element of the structure using the obj[%i%] notation. We are able to access each element of the structure using the obj[%i%] notation. The above command produces the following output. Name = Joe Value = 1 Name = Mark Value = 2 Name = Mohan Value = 3 Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. The first decision-making statement is the ‘if’ statement. The next decision making statement is the If/else statement. Following is the general form of this statement. Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. In batch script, the following types of operators are possible. Arithmetic operators Relational operators Logical operators Assignment operators Bitwise operators Batch script language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available. Show Example Relational operators allow of the comparison of objects. Below are the relational operators available. Show Example Logical operators are used to evaluate Boolean expressions. Following are the logical operators available. The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator. Show Example Batch Script language also provides assignment operators. Following are the assignment operators available. Show Example Set /A a = 5 a += 3 Output will be 8 Set /A a = 5 a -= 3 Output will be 2 Set /A a = 5 a *= 3 Output will be 15 Set /A a = 6 a/ = 3 Output will be 2 Set /A a = 5 a% = 3 Output will be 2 Bitwise operators are also possible in batch script. Following are the operators available. Show Example Following is the truth table showcasing these operators. The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system. This command gets the system date. DATE @echo off echo %DATE% The current date will be displayed in the command prompt. For example, Mon 12/28/2015 This command sets or displays the time. TIME @echo off echo %TIME% The current system time will be displayed. For example, 22:06:52.87 Following are some implementations which can be used to get the date and time in different formats. @echo off echo/Today is: %year%-%month%-%day% goto :EOF setlocal ENABLEEXTENSIONS set t = 2&if "%date%z" LSS "A" set t = 1 for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( set %%a=%%d&set %%b=%%e&set %%c=%%f)) endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF The above command produces the following output. Today is: 2015-12-30 There are three universal “files” for keyboard input, printing text on the screen and printing errors on the screen. The “Standard In” file, known as stdin, contains the input to the program/script. The “Standard Out” file, known as stdout, is used to write output for display on the screen. Finally, the “Standard Err” file, known as stderr, contains any error messages for display on the screen. Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2. One common practice in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. The following example shows how this can be done. Dir C:\ > list.txt In the above example, the stdout of the command Dir C:\ is redirected to the file list.txt. If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt. Dir C:\ 2> list.txt One can even combine the stdout and stderr streams using the file number and the ‘&’ prefix. Following is an example. DIR C:\ > lists.txt 2>&1 The pseudo file NUL is used to discard any output from a program. The following example shows that the output of the command DIR is discarded by sending the output to NUL. Dir C:\ > NUL To work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt’s own stdin, called CON. The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt. TYPE CON > lists.txt By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly. Following are the common exit code and their description. 9009 0x2331 221225495 0xC0000017 -1073741801 Not enough virtual memory is available. It indicates that Windows has run out of memory. 3221225786 0xC000013A -1073741510 3221225794 0xC0000142 -1073741502 The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. By default, the way to check for the ERRORLEVEL is via the following code. IF %ERRORLEVEL% NEQ 0 ( DO_Something ) It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes. Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers. Let’s look at a quick example on how to check for error codes from a batch file. Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9. if not exist c:\lists.txt exit 7 if not defined userprofile exit 9 exit 0 Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0. Call Find.cmd if errorlevel gtr 0 exit echo “Successful completion” In the above program, we can have the following scenarios as the output − If the file c:\lists.txt does not exist, then nothing will be displayed in the console output. If the file c:\lists.txt does not exist, then nothing will be displayed in the console output. If the variable userprofile does not exist, then nothing will be displayed in the console output. If the variable userprofile does not exist, then nothing will be displayed in the console output. If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt. If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt. In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements. There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels. The "FOR" construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values. The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement. Following is the classic ‘for’ statement which is available in most programming languages. The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments. @ECHO OFF :Loop IF "%1"=="" GOTO completed FOR %%F IN (%1) DO echo %%F SHIFT GOTO Loop :completed Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3. 1 2 3 The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop. A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function. As like any other languages, functions in Batch Script follows the same procedure − Function Declaration − It tells the compiler about a function's name, return type, and parameters. Function Declaration − It tells the compiler about a function's name, return type, and parameters. Function Definition − It provides the actual body of the function. Function Definition − It provides the actual body of the function. In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input 'parameters' to the function, process the functions in the main body, and pass back the values to the functions as output 'return types'. Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass its input values (known as arguments) that matches the types of the function's parameters. Following is the syntax of a simple function. :function_name Do_something EXIT /B 0 The function_name is the name given to the function which should have some meaning to match what the function actually does. The function_name is the name given to the function which should have some meaning to match what the function actually does. The EXIT statement is used to ensure that the function exits properly. The EXIT statement is used to ensure that the function exits properly. Following is an example of a simple function. :Display SET /A index=2 echo The value of index is %index% EXIT /B 0 A function is called in Batch Script by using the call command. Functions can work with parameters by simply passing them when a call is made to the function. Functions can work with return values by simply passing variables names Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. In Batch Script, it is possible to perform the normal file I/O operations that would be expected in any programming language. The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. Reading of files in a batch script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. For deleting files, Batch Script provides the DEL command. For renaming files, Batch Script provides the REN or RENAME command. For moving files, Batch Script provides the MOVE command. The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation. In Batch Script, it is possible to perform the normal folder based operations that would be expected in any programming language. The creation of a folder is done with the assistance of the MD (Make directory) command. The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory. For deleting folders, Batch Scripting provides the DEL command. For renaming folders, Batch Script provides the REN or RENAME command. For moving folders, Batch Script provides the MOVE command. In this chapter, we will discuss the various processes involved in Batch Script. In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system. TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH] /S system Specifies the remote system to connect to /U [domain\]user Specifies the user context under which the command should execute. /P [password] Specifies the password for the given user context. Prompts for input if omitted. /M [module] Lists all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed. /SVC Displays services hosted in each process. /V Displays verbose task information. /FI filter Displays a set of tasks that match a given criteria specified by the filter. /FO format Specifies the output format. Valid values: "TABLE", "LIST", "CSV". /NH Specifies that the "Column Header" should not show in the output. Valid only for "TABLE" and "CSV" formats. TASKLIST The above command will get the list of all the processes running on your local system. Following is a snapshot of the output which is rendered when the above command is run as it is. As you can see from the following output, not only do you get the various processes running on your system, you also get the memory usage of each process. Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ System Idle Process 0 Services 0 4 K System 4 Services 0 272 K smss.exe 344 Services 0 1,040 K csrss.exe 528 Services 0 3,892 K csrss.exe 612 Console 1 41,788 K wininit.exe 620 Services 0 3,528 K winlogon.exe 648 Console 1 5,884 K services.exe 712 Services 0 6,224 K lsass.exe 720 Services 0 9,712 K svchost.exe 788 Services 0 10,048 K svchost.exe 832 Services 0 7,696 K dwm.exe 916 Console 1 117,440 K nvvsvc.exe 932 Services 0 6,692 K nvxdsync.exe 968 Console 1 16,328 K nvvsvc.exe 976 Console 1 12,756 K svchost.exe 1012 Services 0 21,648 K svchost.exe 236 Services 0 33,864 K svchost.exe 480 Services 0 11,152 K svchost.exe 1028 Services 0 11,104 K svchost.exe 1048 Services 0 16,108 K wlanext.exe 1220 Services 0 12,560 K conhost.exe 1228 Services 0 2,588 K svchost.exe 1276 Services 0 13,888 K svchost.exe 1420 Services 0 13,488 K spoolsv.exe 1556 Services 0 9,340 K tasklist > process.txt The above command takes the output displayed by tasklist and saves it to the process.txt file. tasklist /fi "memusage gt 40000" The above command will only fetch those processes whose memory is greater than 40MB. Following is a sample output that can be rendered. Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ dwm.exe 916 Console 1 127,912 K explorer.exe 2904 Console 1 125,868 K ServerManager.exe 1836 Console 1 59,796 K WINWORD.EXE 2456 Console 1 144,504 K chrome.exe 4892 Console 1 123,232 K chrome.exe 4976 Console 1 69,412 K chrome.exe 1724 Console 1 76,416 K chrome.exe 3992 Console 1 56,156 K chrome.exe 1168 Console 1 233,628 K chrome.exe 816 Console 1 66,808 K Allows a user running Microsoft Windows XP professional, Windows 2003, or later to kill a task from a Windows command line by process id (PID) or image name. The command used for this purpose is the TASKILL command. TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F] /S system Specifies the remote system to connect to /U [domain\]user Specifies the user context under which the command should execute. /P [password] Specifies the password for the given user context. Prompts for input if omitted. /FI FilterName Applies a filter to select a set of tasks. Allows "*" to be used. ex. imagename eq acme* See below filters for additional information and examples. /PID processID Specifies the PID of the process to be terminated. Use TaskList to get the PID. /IM ImageName Specifies the image name of the process to be terminated. Wildcard '*' can be used to specify all tasks or image names. /T Terminates the specified process and any child processes which were started by it. /F Specifies to forcefully terminate the process(es). taskkill /f /im notepad.exe The above command kills the open notepad task, if open. taskill /pid 9214 The above command kills a process which has a process of 9214. DOS scripting also has the availability to start a new process altogether. This is achieved by using the START command. START "title" [/D path] [options] "command" [parameters] Wherein title − Text for the CMD window title bar (required.) title − Text for the CMD window title bar (required.) path − Starting directory. path − Starting directory. command − The command, batch file or executable program to run. command − The command, batch file or executable program to run. parameters − The parameters passed to the command. parameters − The parameters passed to the command. /MIN Start window Minimized /MAX Start window maximized. /LOW Use IDLE priority class. /NORMAL Use NORMAL priority class. /ABOVENORMAL Use ABOVENORMAL priority class. /BELOWNORMAL Use BELOWNORMAL priority class. /HIGH Use HIGH priority class. /REALTIME Use REALTIME priority class. START "Test Batch Script" /Min test.bat The above command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”. START "" "C:\Program Files\Microsoft Office\Winword.exe" "D:\test\TESTA.txt" The above command will actually run Microsoft word in another process and then open the file TESTA.txt in MS Word. Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing. Dir /w Suppose if we were to create a shortcut to this command as follows. dw = dir /w When we want to execute the dir /w command, we can simply type in the word dw. The word ‘dw’ has now become an alias to the command Dir /w. Alias are managed by using the doskey command. DOSKEY [options] [macroname=[text]] Wherein macroname − A short name for the macro. macroname − A short name for the macro. text − The commands you want to recall. text − The commands you want to recall. Following are the description of the options which can be presented to the DOSKEY command. /REINSTALL Installs a new copy of Doskey /LISTSIZE = size Sets size of command history buffer. /MACROS Displays all Doskey macros. /MACROS:ALL Displays all Doskey macros for all executables which have Doskey macros. /MACROS:exename Displays all Doskey macros for the given executable. /HISTORY Displays all commands stored in memory. /INSERT Specifies that new text you type is inserted in old text. /OVERSTRIKE Specifies that new text overwrites old text. /EXENAME = exename Specifies the executable. /MACROFILE = filename Specifies a file of macros to install. macroname Specifies a name for a macro you create. text Specifies commands you want to record. Create a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command. @echo off doskey cd = cd/test doskey d = dir Once you execute the command, you will able to run these aliases in the command prompt. The following screenshot shows that after the above created batch file is executed, you can freely enter the ‘d’ command and it will give you the directory listing which means that your alias has been created. An alias or macro can be deleted by setting the value of the macro to NULL. @echo off doskey cd = cd/test doskey d = dir d= In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted. An alias or macro can be replaced by setting the value of the macro to the new desired value. @echo off doskey cd = cd/test doskey d = dir d = dir /w In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value. Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe. Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers. Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) − Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings. Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings. Device setup classes. Device setup classes. The devices in a device setup class. The devices in a device setup class. INF files and device driver files. INF files and device driver files. Details of driver packages. Details of driver packages. Hardware resources. Hardware resources. Device status. Device status. Expected driver stack. Expected driver stack. Third-party driver packages in the driver store. Third-party driver packages in the driver store. Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class. Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class. Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways − Enable a device. Disable a device. Update drivers (interactive and non-interactive). Install a device (create a devnode and install software). Remove a device from the device tree and delete its device stack. Rescan for Plug and Play devices. Add, delete, and reorder the hardware IDs of root-enumerated devices. Change the upper and lower filter drivers for a device setup class. Add and delete third-party driver packages from the driver store. Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways − Enable a device. Enable a device. Disable a device. Disable a device. Update drivers (interactive and non-interactive). Update drivers (interactive and non-interactive). Install a device (create a devnode and install software). Install a device (create a devnode and install software). Remove a device from the device tree and delete its device stack. Remove a device from the device tree and delete its device stack. Rescan for Plug and Play devices. Rescan for Plug and Play devices. Add, delete, and reorder the hardware IDs of root-enumerated devices. Add, delete, and reorder the hardware IDs of root-enumerated devices. Change the upper and lower filter drivers for a device setup class. Change the upper and lower filter drivers for a device setup class. Add and delete third-party driver packages from the driver store. Add and delete third-party driver packages from the driver store. DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed. %WindowsSdkDir%\tools\x64\devcon.exe %WindowsSdkDir%\tools\x86\devcon.exe %WindowsSdkDir%\tools\arm\devcon.exe devcon [/m:\\computer] [/r] command [arguments] wherein /m:\\computer − Runs the command on the specified remote computer. The backslashes are required. /m:\\computer − Runs the command on the specified remote computer. The backslashes are required. /r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective. /r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective. command − Specifies a DevCon command. command − Specifies a DevCon command. To list and display information about devices on the computer, use the following commands − DevCon HwIDs DevCon Classes DevCon ListClass DevCon DriverFiles DevCon DriverNodes DevCon Resources DevCon Stack DevCon Status DevCon Dp_enum To list and display information about devices on the computer, use the following commands − DevCon HwIDs DevCon HwIDs DevCon Classes DevCon Classes DevCon ListClass DevCon ListClass DevCon DriverFiles DevCon DriverFiles DevCon DriverNodes DevCon DriverNodes DevCon Resources DevCon Resources DevCon Stack DevCon Stack DevCon Status DevCon Status DevCon Dp_enum DevCon Dp_enum To search for information about devices on the computer, use the following commands − DevCon Find DevCon FindAll To search for information about devices on the computer, use the following commands − DevCon Find DevCon Find DevCon FindAll DevCon FindAll To manipulate the device or change its configuration, use the following commands − DevCon Enable DevCon Disable DevCon Update DevCon UpdateNI DevCon Install DevCon Remove DevCon Rescan DevCon Restart DevCon Reboot DevCon SetHwID DevCon ClassFilter DevCon Dp_add DevCon Dp_delete To manipulate the device or change its configuration, use the following commands − DevCon Enable DevCon Enable DevCon Disable DevCon Disable DevCon Update DevCon Update DevCon UpdateNI DevCon UpdateNI DevCon Install DevCon Install DevCon Remove DevCon Remove DevCon Rescan DevCon Rescan DevCon Restart DevCon Restart DevCon Reboot DevCon Reboot DevCon SetHwID DevCon SetHwID DevCon ClassFilter DevCon ClassFilter DevCon Dp_add DevCon Dp_add DevCon Dp_delete DevCon Dp_delete Following are some examples on how the DevCon command is used. List all driver files The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt. devcon driverfiles * > driverfiles.txt The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file. devcon status * > status.txt The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective. devcon /r enable = Printer The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b). devcon /r install c:\windows\inf\keyboard.inf *PNP030b The following command will scan the computer for new devices. devcon scan The following command will rescan the computer for new devices. devcon rescan The Registry is one of the key elements on a windows system. It contains a lot of information on various aspects of the operating system. Almost all applications installed on a windows system interact with the registry in some form or the other. The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows' path names, using backslashes to indicate levels of hierarchy. This chapter looks at various functions such as querying values, adding, deleting and editing values from the registry. Reading from the registry is done via the REG QUERY command. Adding to the registry is done via the REG ADD command. Deleting from the registry is done via the REG DEL command. Copying from the registry is done via the REG COPY command. Comparing registry keys is done via the REG COMPARE command. Batch script has the facility to work with network settings. The NET command is used to update, fix, or view the network or network settings. This chapter looks at the different options available for the net command. View the current password & logon restrictions for the computer. Displays your current server or workgroup settings. Adds or removes a computer attached to the windows domain controller. This command can be used for the following View the details of a particular user account. This command is used to stop and start a particular service. Display network statistics of the workstation or server. Connects or disconnects your computer from a shared resource or displays information about your connections. Printing can also be controlled from within Batch Script via the NET PRINT command. PRINT [/D:device] [[drive:][path]filename[...]] Where /D:device - Specifies a print device. print c:\example.txt /c /d:lpt1 The above command will print the example.txt file to the parallel port lpt1. As of Windows 2000, many, but not all, printer settings can be configured from Windows's command line using PRINTUI.DLL and RUNDLL32.EXE RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ] Where some of the options available are the following − /dl − Delete local printer. /dl − Delete local printer. /dn − Delete network printer connection. /dn − Delete network printer connection. /dd − Delete printer driver. /dd − Delete printer driver. /e − Display printing preferences. /e − Display printing preferences. /f[file] − Either inf file or output file. /f[file] − Either inf file or output file. /F[file] − Location of an INF file that the INF file specified with /f may depend on. /F[file] − Location of an INF file that the INF file specified with /f may depend on. /ia − Install printer driver using inf file. /ia − Install printer driver using inf file. /id − Install printer driver using add printer driver wizard. /id − Install printer driver using add printer driver wizard. /if − Install printer using inf file. /if − Install printer using inf file. /ii − Install printer using add printer wizard with an inf file. /ii − Install printer using add printer wizard with an inf file. /il − Install printer using add printer wizard. /il − Install printer using add printer wizard. /in − Add network printer connection. /in − Add network printer connection. /ip − Install printer using network printer installation wizard. /ip − Install printer using network printer installation wizard. /k − Print test page to specified printer, cannot be combined with command when installing a printer. /k − Print test page to specified printer, cannot be combined with command when installing a printer. /l[path] − Printer driver source path. /l[path] − Printer driver source path. /m[model] − Printer driver model name. /m[model] − Printer driver model name. /n[name] − Printer name. /n[name] − Printer name. /o − Display printer queue view. /o − Display printer queue view. /p − Display printer properties. /p − Display printer properties. /Ss − Store printer settings into a file. /Ss − Store printer settings into a file. /Sr − Restore printer settings from a file. /Sr − Restore printer settings from a file. /y − Set printer as the default. /y − Set printer as the default. /Xg − Get printer settings. /Xg − Get printer settings. /Xs − Set printer settings. /Xs − Set printer settings. There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing. The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings. SET PrinterName = Test Printer SET file=%TEMP%\Prt.txt RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n "%PrinterName%" /f "%file%" /q IF EXIST "%file%" ( ECHO %PrinterName% printer exists ) ELSE ( ECHO %PrinterName% printer does NOT exists ) The above command will do the following − It will first set the printer name and set a file name which will hold the settings of the printer. It will first set the printer name and set a file name which will hold the settings of the printer. The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt Debugging a batch script becomes important when you are working on a big complex batch script. Following are the ways in which you can debug the batch file. A very simple debug option is to make use of echo command in your batch script wherever possible. It will display the message in the command prompt and help you debug where things have gone wrong. Here is a simple example that displays even numbers based on the input given. The echo command is used to display the result and also if the input is not given. Similarly, the echo command can be used in place when you think that the error can happen. For example, if the input given is a negative number, less than 2, etc. @echo off if [%1] == [] ( echo input value not provided goto stop ) rem Display numbers for /l %%n in (2,2,%1) do ( echo %%n ) :stop pause C:\>test.bat 10 2 4 6 8 10 22 Press any key to continue ... Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing. In the example below, the batch script is paused as the input value is mandatory and not provided. @echo off if [%1] == [] ( echo input value not provided goto stop ) else ( echo "Valid value" ) :stop pause C:\>test.bat input value not provided Press any key to continue.. It might get hard to debug the error just looking at a bunch of echo displayed on the command prompt. Another easy way out is to log those messages in another file and view it step by step to understand what went wrong. Here is an example, consider the following test.bat file: net statistics /Server The command given in the .bat file is wrong. Let us log the message and see what we get. Execute the following command in your command line: C:\>test.bat > testlog.txt 2> testerrors.txt The file testerrors.txt will display the error messages as shown below: The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. Looking at the above file the developer can fix the program and execute again. Errorlevel returns 0 if the command executes successfully and 1 if it fails. Consider the following example: @echo off PING google.com if errorlevel 1 GOTO stop :stop echo Unable to connect to google.com pause During execution, you can see errors as well as logs: C:\>test.bat > testlog.txt testlog.txt Pinging google.com [172.217.26.238] with 32 bytes of data: Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 Reply from 172.217.26.238: bytes=32 time=108ms TTL=111 Ping statistics for 172.217.26.238: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 82ms, Maximum = 160ms, Average = 117ms Connected successfully Press any key to continue . . . In case of failure, you will see the following logs inside testlog.txt. Ping request could not find host google.com. Please check the name and try again. Unable to connect to google.com Press any key to continue . . . Logging in is possible in Batch Script by using the redirection command. test.bat > testlog.txt 2> testerrors.txt Create a file called test.bat and enter the following command in the file. net statistics /Server The above command has an error because the option to the net statistics command is given in the wrong way. If the command with the above test.bat file is run as test.bat > testlog.txt 2> testerrors.txt And you open the file testerrors.txt, you will see the following error. The option /SERVER is unknown. The syntax of this command is − NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. If you open the file called testlog.txt, it will show you a log of what commands were executed. C:\tp>net statistics /Server Print Add Notes Bookmark this page
[ { "code": null, "e": 2524, "s": 2169, "text": "Batch Script is incorporated to automate command sequences which are repetitive in nature. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. In most organizations, Batch Script is incorporated in some way or the other to automate stuff." }, { "code": null, "e": 2567, "s": 2524, "text": "Some of the features of Batch Script are −" }, { "code": null, "e": 2631, "s": 2567, "text": "Can read inputs from users so that it can be processed further." }, { "code": null, "e": 2695, "s": 2631, "text": "Can read inputs from users so that it can be processed further." }, { "code": null, "e": 2786, "s": 2695, "text": "Has control structures such as for, if, while, switch for better automating and scripting." }, { "code": null, "e": 2877, "s": 2786, "text": "Has control structures such as for, if, while, switch for better automating and scripting." }, { "code": null, "e": 2934, "s": 2877, "text": "Supports advanced features such as Functions and Arrays." }, { "code": null, "e": 2991, "s": 2934, "text": "Supports advanced features such as Functions and Arrays." }, { "code": null, "e": 3021, "s": 2991, "text": "Supports regular expressions." }, { "code": null, "e": 3051, "s": 3021, "text": "Supports regular expressions." }, { "code": null, "e": 3101, "s": 3051, "text": "Can include other programming codes such as Perl." }, { "code": null, "e": 3151, "s": 3101, "text": "Can include other programming codes such as Perl." }, { "code": null, "e": 3197, "s": 3151, "text": "Some of the common uses of Batch Script are −" }, { "code": null, "e": 3240, "s": 3197, "text": "Setting up servers for different purposes." }, { "code": null, "e": 3283, "s": 3240, "text": "Setting up servers for different purposes." }, { "code": null, "e": 3364, "s": 3283, "text": "Automating housekeeping activities such as deleting unwanted files or log files." }, { "code": null, "e": 3445, "s": 3364, "text": "Automating housekeeping activities such as deleting unwanted files or log files." }, { "code": null, "e": 3520, "s": 3445, "text": "Automating the deployment of applications from one environment to another." }, { "code": null, "e": 3595, "s": 3520, "text": "Automating the deployment of applications from one environment to another." }, { "code": null, "e": 3644, "s": 3595, "text": "Installing programs on various machines at once." }, { "code": null, "e": 3693, "s": 3644, "text": "Installing programs on various machines at once." }, { "code": null, "e": 4084, "s": 3693, "text": "Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe." }, { "code": null, "e": 4436, "s": 4084, "text": "Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file's path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory." }, { "code": null, "e": 4588, "s": 4436, "text": ":: Deletes All files in the Current Directory With Prompts and Warnings\n::(Hidden, System, and Read-Only Files are Not Affected)\n:: @ECHO OFF\nDEL . DR\n" }, { "code": null, "e": 4651, "s": 4588, "text": "This chapter explains the environment related to Batch Script." }, { "code": null, "e": 4928, "s": 4651, "text": "Typically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment." }, { "code": null, "e": 4981, "s": 4928, "text": "Following are the different ways to launch cmd.exe −" }, { "code": null, "e": 5052, "s": 4981, "text": "Method 1 − Go to C:\\Windows\\System32 and double click on the cmd file." }, { "code": null, "e": 5174, "s": 5052, "text": "Method 2 − Via the run command – The following snapshot shows to find the command prompt(cmd.exe) on Windows server 2012." }, { "code": null, "e": 5317, "s": 5174, "text": "Once the cmd.exe is launched, you will be presented with the following screen. This will be your environment for executing your batch scripts." }, { "code": null, "e": 5682, "s": 5317, "text": "In order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the batch file is stored in the location C:\\Application\\bin, you would need to follow these instructions for the PATH variable inclusion." }, { "code": null, "e": 5759, "s": 5682, "text": "In this chapter, we will look at some of the frequently used batch commands." }, { "code": null, "e": 5821, "s": 5759, "text": "This batch command shows the version of MS-DOS you are using." }, { "code": null, "e": 5959, "s": 5821, "text": "This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association." }, { "code": null, "e": 6063, "s": 5959, "text": "This batch command helps in making changes to a different directory, or displays the current directory." }, { "code": null, "e": 6101, "s": 6063, "text": "This batch command clears the screen." }, { "code": null, "e": 6178, "s": 6101, "text": "This batch command is used for copying files from one location to the other." }, { "code": null, "e": 6232, "s": 6178, "text": "This batch command deletes files and not directories." }, { "code": null, "e": 6286, "s": 6232, "text": "This batch command lists the contents of a directory." }, { "code": null, "e": 6335, "s": 6286, "text": "This batch command help to find the system date." }, { "code": null, "e": 6409, "s": 6335, "text": "This batch command displays messages, or turns command echoing on or off." }, { "code": null, "e": 6451, "s": 6409, "text": "This batch command exits the DOS console." }, { "code": null, "e": 6519, "s": 6451, "text": "This batch command creates a new directory in the current location." }, { "code": null, "e": 6586, "s": 6519, "text": "This batch command moves files or directories between directories." }, { "code": null, "e": 6641, "s": 6586, "text": "This batch command displays or sets the path variable." }, { "code": null, "e": 6722, "s": 6641, "text": "This batch command prompts the user and waits for a line of input to be entered." }, { "code": null, "e": 6792, "s": 6722, "text": "This batch command can be used to change or reset the cmd.exe prompt." }, { "code": null, "e": 6897, "s": 6792, "text": "This batch command removes directories, but the directories need to be empty before they can be removed." }, { "code": null, "e": 6927, "s": 6897, "text": "Renames files and directories" }, { "code": null, "e": 7040, "s": 6927, "text": "This batch command is used for remarks in batch files, preventing the content of the remark from being executed." }, { "code": null, "e": 7112, "s": 7040, "text": "This batch command starts a program in new window, or opens a document." }, { "code": null, "e": 7158, "s": 7112, "text": "This batch command sets or displays the time." }, { "code": null, "e": 7230, "s": 7158, "text": "This batch command prints the content of a file or files to the output." }, { "code": null, "e": 7277, "s": 7230, "text": "This batch command displays the volume labels." }, { "code": null, "e": 7346, "s": 7277, "text": "Displays or sets the attributes of the files in the curret directory" }, { "code": null, "e": 7399, "s": 7346, "text": "This batch command checks the disk for any problems." }, { "code": null, "e": 7458, "s": 7399, "text": "This batch command provides a list of options to the user." }, { "code": null, "e": 7521, "s": 7458, "text": "This batch command invokes another instance of command prompt." }, { "code": null, "e": 7581, "s": 7521, "text": "This batch command compares 2 files based on the file size." }, { "code": null, "e": 7671, "s": 7581, "text": "This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system." }, { "code": null, "e": 7747, "s": 7671, "text": "This batch command shows all installed device drivers and their properties." }, { "code": null, "e": 7817, "s": 7747, "text": "This batch command extracts files from compressed .cab cabinet files." }, { "code": null, "e": 7904, "s": 7817, "text": "This batch command searches for a string in files or input, outputting matching lines." }, { "code": null, "e": 8057, "s": 7904, "text": "This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk." }, { "code": null, "e": 8121, "s": 8057, "text": "This batch command shows the list of Windows-supplied commands." }, { "code": null, "e": 8242, "s": 8121, "text": "This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection." }, { "code": null, "e": 8297, "s": 8242, "text": "This batch command adds, sets or removes a disk label." }, { "code": null, "e": 8380, "s": 8297, "text": "This batch command displays the contents of a file or files, one screen at a time." }, { "code": null, "e": 8446, "s": 8380, "text": "Provides various network services, depending on the command used." }, { "code": null, "e": 8538, "s": 8446, "text": "This batch command sends ICMP/IP \"echo\" packets over the network to the designated address." }, { "code": null, "e": 8610, "s": 8538, "text": "This batch command shuts down a computer, or logs off the current user." }, { "code": null, "e": 8763, "s": 8610, "text": "This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console." }, { "code": null, "e": 8880, "s": 8763, "text": "This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment." }, { "code": null, "e": 8959, "s": 8880, "text": "This batch command shows configuration of a computer and its operating system." }, { "code": null, "e": 9002, "s": 8959, "text": "This batch command ends one or more tasks." }, { "code": null, "e": 9076, "s": 9002, "text": "This batch command lists tasks, including task name and process id (PID)." }, { "code": null, "e": 9148, "s": 9076, "text": "This batch command copies files and directories in a more advanced way." }, { "code": null, "e": 9266, "s": 9148, "text": "This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth." }, { "code": null, "e": 9333, "s": 9266, "text": "This batch command lists the actual differences between two files." }, { "code": null, "e": 9408, "s": 9333, "text": "This batch command shows and configures the properties of disk partitions." }, { "code": null, "e": 9475, "s": 9408, "text": "This batch command sets the title displayed in the console window." }, { "code": null, "e": 9541, "s": 9475, "text": "Displays the list of environment variables on the current system." }, { "code": null, "e": 9626, "s": 9541, "text": "In this chapter, we will learn how to create, save, execute, and modify batch files." }, { "code": null, "e": 9829, "s": 9626, "text": "Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements." }, { "code": null, "e": 9985, "s": 9829, "text": ":: Deletes All files in the Current Directory With Prompts and Warnings \n::(Hidden, System, and Read-Only Files are Not Affected) \n:: \n@ECHO OFF \nDEL . \nDR" }, { "code": null, "e": 10177, "s": 9985, "text": "After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −" }, { "code": null, "e": 10290, "s": 10177, "text": "Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts." }, { "code": null, "e": 10403, "s": 10290, "text": "Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts." }, { "code": null, "e": 10496, "s": 10403, "text": "Don’t name them after common batch files which are available in the system such as ping.cmd." }, { "code": null, "e": 10589, "s": 10496, "text": "Don’t name them after common batch files which are available in the system such as ping.cmd." }, { "code": null, "e": 10702, "s": 10589, "text": "The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind." }, { "code": null, "e": 10764, "s": 10702, "text": "Remember to put the .bat or .cmd at the end of the file name." }, { "code": null, "e": 10813, "s": 10764, "text": "Choose the “Save as type” option as “All Files”." }, { "code": null, "e": 10852, "s": 10813, "text": "Put the entire file name in quotes “”." }, { "code": null, "e": 10902, "s": 10852, "text": "Following are the steps to execute a batch file −" }, { "code": null, "e": 10946, "s": 10902, "text": "Step 1 − Open the command prompt (cmd.exe)." }, { "code": null, "e": 10990, "s": 10946, "text": "Step 1 − Open the command prompt (cmd.exe)." }, { "code": null, "e": 11057, "s": 10990, "text": "Step 2 − Go to the location where the .bat or .cmd file is stored." }, { "code": null, "e": 11124, "s": 11057, "text": "Step 2 − Go to the location where the .bat or .cmd file is stored." }, { "code": null, "e": 11246, "s": 11124, "text": "Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file." }, { "code": null, "e": 11368, "s": 11246, "text": "Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file." }, { "code": null, "e": 11430, "s": 11368, "text": "Following are the steps for modifying an existing batch file." }, { "code": null, "e": 11462, "s": 11430, "text": "Step 1 − Open windows explorer." }, { "code": null, "e": 11494, "s": 11462, "text": "Step 1 − Open windows explorer." }, { "code": null, "e": 11561, "s": 11494, "text": "Step 2 − Go to the location where the .bat or .cmd file is stored." }, { "code": null, "e": 11628, "s": 11561, "text": "Step 2 − Go to the location where the .bat or .cmd file is stored." }, { "code": null, "e": 11761, "s": 11628, "text": "Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing." }, { "code": null, "e": 11894, "s": 11761, "text": "Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing." }, { "code": null, "e": 11976, "s": 11894, "text": "Normally, the first line in a batch file often consists of the following command." }, { "code": null, "e": 11987, "s": 11976, "text": "@echo off\n" }, { "code": null, "e": 12291, "s": 11987, "text": "By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command \"echo off\" turns off the display for the whole script, except for the \"echo off\" command itself. The \"at\" sign \"@\" in front makes the command apply to itself as well." }, { "code": null, "e": 12573, "s": 12291, "text": "Very often batch files also contains lines that start with the \"Rem\" command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments." }, { "code": null, "e": 12709, "s": 12573, "text": "Let’s construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as “List.cmd”." }, { "code": null, "e": 12739, "s": 12709, "text": "The code does the following −" }, { "code": null, "e": 12834, "s": 12739, "text": "Uses the echo off command to ensure that the commands are not shown when the code is executed." }, { "code": null, "e": 12929, "s": 12834, "text": "Uses the echo off command to ensure that the commands are not shown when the code is executed." }, { "code": null, "e": 13012, "s": 12929, "text": "The Rem command is used to add a comment to say what exactly this batch file does." }, { "code": null, "e": 13095, "s": 13012, "text": "The Rem command is used to add a comment to say what exactly this batch file does." }, { "code": null, "e": 13174, "s": 13095, "text": "The dir command is used to take the contents of the location C:\\Program Files." }, { "code": null, "e": 13253, "s": 13174, "text": "The dir command is used to take the contents of the location C:\\Program Files." }, { "code": null, "e": 13326, "s": 13253, "text": "The ‘>’ command is used to redirect the output to the file C:\\lists.txt." }, { "code": null, "e": 13399, "s": 13326, "text": "The ‘>’ command is used to redirect the output to the file C:\\lists.txt." }, { "code": null, "e": 13483, "s": 13399, "text": "Finally, the echo command is used to tell the user that the operation is completed." }, { "code": null, "e": 13567, "s": 13483, "text": "Finally, the echo command is used to tell the user that the operation is completed." }, { "code": null, "e": 13725, "s": 13567, "text": "@echo off \nRem This is for listing down all the files in the directory Program files \ndir \"C:\\Program Files\" > C:\\lists.txt \necho \"The program has completed\"" }, { "code": null, "e": 13927, "s": 13725, "text": "When the above command is executed, the names of the files in C:\\Program Files will be sent to the file C:\\Lists.txt and in the command prompt the message “The program has completed” will be displayed." }, { "code": null, "e": 14091, "s": 13927, "text": "There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command." }, { "code": null, "e": 14309, "s": 14091, "text": "Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on." }, { "code": null, "e": 14433, "s": 14309, "text": "The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen." }, { "code": null, "e": 14470, "s": 14433, "text": "@echo off \necho %1 \necho %2 \necho %3" }, { "code": null, "e": 14564, "s": 14470, "text": "If the above batch script is stored in a file called test.bat and we were to run the batch as" }, { "code": null, "e": 14580, "s": 14564, "text": "Test.bat 1 2 3\n" }, { "code": null, "e": 14684, "s": 14580, "text": "Following is a screenshot of how this would look in the command prompt when the batch file is executed." }, { "code": null, "e": 14733, "s": 14684, "text": "The above command produces the following output." }, { "code": null, "e": 14742, "s": 14733, "text": "1 \n2 \n3\n" }, { "code": null, "e": 14773, "s": 14742, "text": "If we were to run the batch as" }, { "code": null, "e": 14790, "s": 14773, "text": "Example 1 2 3 4\n" }, { "code": null, "e": 14887, "s": 14790, "text": "The output would still remain the same as above. However, the fourth parameter would be ignored." }, { "code": null, "e": 15009, "s": 14887, "text": "The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command." }, { "code": null, "e": 15037, "s": 15009, "text": "set /A variable-name=value\n" }, { "code": null, "e": 15044, "s": 15037, "text": "where," }, { "code": null, "e": 15103, "s": 15044, "text": "variable-name is the name of the variable you want to set." }, { "code": null, "e": 15162, "s": 15103, "text": "variable-name is the name of the variable you want to set." }, { "code": null, "e": 15225, "s": 15162, "text": "value is the value which needs to be set against the variable." }, { "code": null, "e": 15288, "s": 15225, "text": "value is the value which needs to be set against the variable." }, { "code": null, "e": 15357, "s": 15288, "text": "/A – This switch is used if the value needs to be numeric in nature." }, { "code": null, "e": 15426, "s": 15357, "text": "/A – This switch is used if the value needs to be numeric in nature." }, { "code": null, "e": 15496, "s": 15426, "text": "The following example shows a simple way the set command can be used." }, { "code": null, "e": 15547, "s": 15496, "text": "@echo off \nset message=Hello World \necho %message%" }, { "code": null, "e": 15652, "s": 15547, "text": "In the above code snippet, a variable called message is defined and set with the value of \"Hello World\"." }, { "code": null, "e": 15757, "s": 15652, "text": "In the above code snippet, a variable called message is defined and set with the value of \"Hello World\"." }, { "code": null, "e": 15854, "s": 15757, "text": "To display the value of the variable, note that the variable needs to be enclosed in the % sign." }, { "code": null, "e": 15951, "s": 15854, "text": "To display the value of the variable, note that the variable needs to be enclosed in the % sign." }, { "code": null, "e": 16000, "s": 15951, "text": "The above command produces the following output." }, { "code": null, "e": 16013, "s": 16000, "text": "Hello World\n" }, { "code": null, "e": 16137, "s": 16013, "text": "In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch." }, { "code": null, "e": 16230, "s": 16137, "text": "The following code shows a simple way in which numeric values can be set with the /A switch." }, { "code": null, "e": 16301, "s": 16230, "text": "@echo off \nSET /A a = 5 \nSET /A b = 10 \nSET /A c = %a% + %b% \necho %c%" }, { "code": null, "e": 16382, "s": 16301, "text": "We are first setting the value of 2 variables, a and b to 5 and 10 respectively." }, { "code": null, "e": 16463, "s": 16382, "text": "We are first setting the value of 2 variables, a and b to 5 and 10 respectively." }, { "code": null, "e": 16521, "s": 16463, "text": "We are adding those values and storing in the variable c." }, { "code": null, "e": 16579, "s": 16521, "text": "We are adding those values and storing in the variable c." }, { "code": null, "e": 16635, "s": 16579, "text": "Finally, we are displaying the value of the variable c." }, { "code": null, "e": 16691, "s": 16635, "text": "Finally, we are displaying the value of the variable c." }, { "code": null, "e": 16736, "s": 16691, "text": "The output of the above program would be 15." }, { "code": null, "e": 16866, "s": 16736, "text": "All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files." }, { "code": null, "e": 17033, "s": 16866, "text": "@echo off \nSET /A a = 5 \nSET /A b = 10 \nSET /A c = %a% + %b% \necho %c% \nSET /A c = %a% - %b% \necho %c% \nSET /A c = %b% / %a% \necho %c% \nSET /A c = %b% * %a% \necho %c%" }, { "code": null, "e": 17082, "s": 17033, "text": "The above command produces the following output." }, { "code": null, "e": 17097, "s": 17082, "text": "15 \n-5 \n2 \n50\n" }, { "code": null, "e": 17416, "s": 17097, "text": "In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed." }, { "code": null, "e": 17901, "s": 17416, "text": "DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script." }, { "code": null, "e": 18015, "s": 17901, "text": "@echo off \nset globalvar = 5\nSETLOCAL\nset var = 13145\nset /A var = %var% + 5\necho %var%\necho %globalvar%\nENDLOCAL" }, { "code": null, "e": 18063, "s": 18015, "text": "Few key things to note about the above program." }, { "code": null, "e": 18157, "s": 18063, "text": "The ‘globalvar’ is defined with a global scope and is available throughout the entire script." }, { "code": null, "e": 18251, "s": 18157, "text": "The ‘globalvar’ is defined with a global scope and is available throughout the entire script." }, { "code": null, "e": 18449, "s": 18251, "text": "The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed." }, { "code": null, "e": 18647, "s": 18449, "text": "The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed." }, { "code": null, "e": 18696, "s": 18647, "text": "The above command produces the following output." }, { "code": null, "e": 18705, "s": 18696, "text": "13150\n5\n" }, { "code": null, "e": 18852, "s": 18705, "text": "You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist." }, { "code": null, "e": 19222, "s": 18852, "text": "If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications." }, { "code": null, "e": 19250, "s": 19222, "text": "@echo off \necho %JAVA_HOME%" }, { "code": null, "e": 19376, "s": 19250, "text": "The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output." }, { "code": null, "e": 19410, "s": 19376, "text": "C:\\Atlassian\\Bitbucket\\4.0.1\\jre\n" }, { "code": null, "e": 19599, "s": 19410, "text": "It’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does." }, { "code": null, "e": 19866, "s": 19599, "text": "For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does." }, { "code": null, "e": 20505, "s": 19866, "text": "ECHO OFF \nIF NOT \"%OS%\"==\"Windows_NT\" GOTO Syntax \nECHO.%* | FIND \"?\" >NUL \nIF NOT ERRORLEVEL 1 GOTO Syntax \nIF NOT [%2]==[] GOTO Syntax \nSETLOCAL \nSET WSS= \nIF NOT [%1]==[] FOR /F \"tokens = 1 delims = \\ \" %%A IN ('ECHO.%~1') DO SET WSS = %%A \nFOR /F \"tokens = 1 delims = \\ \" %%a IN ('NET VIEW ^| FIND /I \"\\\\%WSS%\"') DO FOR /F \n\"tokens = 1 delims = \" %%A IN ('NBTSTAT -a %%a ^| FIND /I /V \"%%a\" ^| FIND \"<03>\"') \nDO ECHO.%%a %%A \nENDLOCAL \nGOTO:EOF \nECHO Display logged on users and their workstations. \nECHO Usage: ACTUSR [ filter ] \nIF \"%OS%\"==\"Windows_NT\" ECHO Where: filter is the first part \nof the computer name^(s^) to be displayed" }, { "code": null, "e": 20734, "s": 20505, "text": "There are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement." }, { "code": null, "e": 20747, "s": 20734, "text": "Rem Remarks\n" }, { "code": null, "e": 20804, "s": 20747, "text": "where ‘Remarks’ is the comments which needs to be added." }, { "code": null, "e": 20874, "s": 20804, "text": "The following example shows a simple way the Rem command can be used." }, { "code": null, "e": 20969, "s": 20874, "text": "@echo off \nRem This program just displays Hello World \nset message=Hello World \necho %message%" }, { "code": null, "e": 21093, "s": 20969, "text": "The above command produces the following output. You will notice that the line with the Rem statement will not be executed." }, { "code": null, "e": 21106, "s": 21093, "text": "Hello World\n" }, { "code": null, "e": 21323, "s": 21106, "text": "The other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement." }, { "code": null, "e": 21335, "s": 21323, "text": ":: Remarks\n" }, { "code": null, "e": 21391, "s": 21335, "text": "where ‘Remarks’ is the comment which needs to be added." }, { "code": null, "e": 21461, "s": 21391, "text": "The following example shows a simple way the Rem command can be used." }, { "code": null, "e": 21557, "s": 21461, "text": "@echo off \n:: This program just displays Hello World \nset message = Hello World \necho %message%" }, { "code": null, "e": 21680, "s": 21557, "text": "The above command produces the following output. You will notice that the line with the :: statement will not be executed." }, { "code": null, "e": 21693, "s": 21680, "text": "Hello World\n" }, { "code": null, "e": 21847, "s": 21693, "text": "Note − If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed." }, { "code": null, "e": 21987, "s": 21847, "text": "Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it." }, { "code": null, "e": 23050, "s": 21987, "text": "::===============================================================\n:: The below example is used to find computer and logged on users\n::\n::===============================================================\nECHO OFF \n:: Windows version check \nIF NOT \"%OS%\"==\"Windows_NT\" GOTO Syntax \nECHO.%* | FIND \"?\" >NUL \n:: Command line parameter check \nIF NOT ERRORLEVEL 1 GOTO Syntax\nIF NOT [%2]==[] GOTO Syntax \n:: Keep variable local \nSETLOCAL \n:: Initialize variable \nSET WSS= \n:: Parse command line parameter \nIF NOT [%1]==[] FOR /F \"tokens = 1 delims = \\ \" %%A IN ('ECHO.%~1') DO SET WSS = %%A \n:: Use NET VIEW and NBTSTAT to find computers and logged on users \nFOR /F \"tokens = 1 delims = \\ \" %%a IN ('NET VIEW ^| FIND /I \"\\\\%WSS%\"') DO FOR /F \n\"tokens = 1 delims = \" %%A IN ('NBTSTAT -a %%a ^| FIND /I /V \"%%a\" ^| FIND \n\"<03>\"') DO ECHO.%%a %%A \n:: Done \nENDLOCAL\nGOTO:EOF \n:Syntax \nECHO Display logged on users and their workstations. \nECHO Usage: ACTUSR [ filter ] \nIF \"%OS%\"==\"Windows_NT\" ECHO Where: filter is the first part of the \ncomputer name^(s^) to be displayed" }, { "code": null, "e": 23184, "s": 23050, "text": "You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable." }, { "code": null, "e": 23266, "s": 23184, "text": "In DOS, a string is an ordered collection of characters, such as \"Hello, World!\"." }, { "code": null, "e": 23319, "s": 23266, "text": "A string can be created in DOS in the following way." }, { "code": null, "e": 23332, "s": 23319, "text": "Empty String" }, { "code": null, "e": 23507, "s": 23332, "text": "String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal." }, { "code": null, "e": 23686, "s": 23507, "text": "You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation." }, { "code": null, "e": 23931, "s": 23686, "text": "In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string." }, { "code": null, "e": 24136, "s": 23931, "text": "A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished." }, { "code": null, "e": 24239, "s": 24136, "text": "This used to align text to the right, which is normally used to improve readability of number columns." }, { "code": null, "e": 24306, "s": 24239, "text": "This is used to extract characters from the beginning of a string." }, { "code": null, "e": 24392, "s": 24306, "text": "This is used to extract a substring via the position of the characters in the string." }, { "code": null, "e": 24484, "s": 24392, "text": "The string substitution feature can also be used to remove a substring from another string." }, { "code": null, "e": 24553, "s": 24484, "text": "This is used to remove the first and the last character of a string." }, { "code": null, "e": 24617, "s": 24553, "text": "This is used to remove all spaces in a string via substitution." }, { "code": null, "e": 24697, "s": 24617, "text": "To replace a substring with another string use the string substitution feature." }, { "code": null, "e": 24758, "s": 24697, "text": "This is used to extract characters from the end of a string." }, { "code": null, "e": 24927, "s": 24758, "text": "Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script." }, { "code": null, "e": 24995, "s": 24927, "text": "Each element of the array needs to be defined with the set command." }, { "code": null, "e": 25072, "s": 24995, "text": "The ‘for’ loop would be required to iterate through the values of the array." }, { "code": null, "e": 25128, "s": 25072, "text": "An array is created by using the following set command." }, { "code": null, "e": 25140, "s": 25128, "text": "set a[0]=1\n" }, { "code": null, "e": 25237, "s": 25140, "text": "Where 0 is the index of the array and 1 is the value assigned to the first element of the array." }, { "code": null, "e": 25395, "s": 25237, "text": "Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented." }, { "code": null, "e": 25469, "s": 25395, "text": "@echo off \nset list = 1 2 3 4 \n(for %%a in (%list%) do ( \n echo %%a \n))" }, { "code": null, "e": 25518, "s": 25469, "text": "The above command produces the following output." }, { "code": null, "e": 25527, "s": 25518, "text": "1\n2\n3\n4\n" }, { "code": null, "e": 25710, "s": 25527, "text": "You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array." }, { "code": null, "e": 25745, "s": 25710, "text": "@echo off \nset a[0]=1 \necho %a[0]%" }, { "code": null, "e": 25989, "s": 25745, "text": "In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let's check the following example to create, initialize and access arrays −" }, { "code": null, "e": 26182, "s": 25989, "text": "@echo off\nset a[0] = 1 \nset a[1] = 2 \nset a[2] = 3 \necho The first element of the array is %a[0]% \necho The second element of the array is %a[1]% \necho The third element of the array is %a[2]%" }, { "code": null, "e": 26231, "s": 26182, "text": "The above command produces the following output." }, { "code": null, "e": 26343, "s": 26231, "text": "The first element of the array is 1 \nThe second element of the array is 2 \nThe third element of the array is 3\n" }, { "code": null, "e": 26462, "s": 26343, "text": "To add an element to the end of the array, you can use the set element along with the last index of the array element." }, { "code": null, "e": 26622, "s": 26462, "text": "@echo off \nset a[0] = 1 \nset a[1] = 2 \nset a[2] = 3 \nRem Adding an element at the end of an array \nSet a[3] = 4 \necho The last element of the array is %a[3]%" }, { "code": null, "e": 26671, "s": 26622, "text": "The above command produces the following output." }, { "code": null, "e": 26707, "s": 26671, "text": "The last element of the array is 4\n" }, { "code": null, "e": 26832, "s": 26707, "text": "You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example −" }, { "code": null, "e": 27027, "s": 26832, "text": "@echo off \nset a[0] = 1 \nset a[1] = 2 \nset a[2] = 3 \nRem Setting the new value for the second element of the array \nSet a[1] = 5 \necho The new value of the second element of the array is %a[1]%" }, { "code": null, "e": 27076, "s": 27027, "text": "The above command produces the following output." }, { "code": null, "e": 27131, "s": 27076, "text": "The new value of the second element of the array is 5\n" }, { "code": null, "e": 27311, "s": 27131, "text": "Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented." }, { "code": null, "e": 27570, "s": 27311, "text": "@echo off \nsetlocal enabledelayedexpansion \nset topic[0] = comments \nset topic[1] = variables \nset topic[2] = Arrays \nset topic[3] = Decision making \nset topic[4] = Time and date \nset topic[5] = Operators \n\nfor /l %%n in (0,1,5) do ( \n echo !topic[%%n]! \n)" }, { "code": null, "e": 27630, "s": 27570, "text": "Following things need to be noted about the above program −" }, { "code": null, "e": 27712, "s": 27630, "text": "Each element of the array needs to be specifically defined using the set command." }, { "code": null, "e": 27794, "s": 27712, "text": "Each element of the array needs to be specifically defined using the set command." }, { "code": null, "e": 27895, "s": 27794, "text": "The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array." }, { "code": null, "e": 27996, "s": 27895, "text": "The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array." }, { "code": null, "e": 28045, "s": 27996, "text": "The above command produces the following output." }, { "code": null, "e": 28117, "s": 28045, "text": "Comments \nvariables \nArrays \nDecision making \nTime and date \nOperators\n" }, { "code": null, "e": 28281, "s": 28117, "text": "The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array." }, { "code": null, "e": 28505, "s": 28281, "text": "@echo off \nset Arr[0] = 1 \nset Arr[1] = 2 \nset Arr[2] = 3 \nset Arr[3] = 4 \nset \"x = 0\" \n:SymLoop \n\nif defined Arr[%x%] ( \n call echo %%Arr[%x%]%% \n set /a \"x+=1\"\n GOTO :SymLoop \n)\necho \"The length of the array is\" %x%" }, { "code": null, "e": 28561, "s": 28505, "text": "Output The above command produces the following output." }, { "code": null, "e": 28591, "s": 28561, "text": "The length of the array is 4\n" }, { "code": null, "e": 28753, "s": 28591, "text": "Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved." }, { "code": null, "e": 29147, "s": 28753, "text": "@echo off \nset len = 3 \nset obj[0].Name = Joe \nset obj[0].ID = 1 \nset obj[1].Name = Mark \nset obj[1].ID = 2 \nset obj[2].Name = Mohan \nset obj[2].ID = 3 \nset i = 0 \n:loop \n\nif %i% equ %len% goto :eof \nset cur.Name= \nset cur.ID=\n\nfor /f \"usebackq delims==.tokens=1-3\" %%j in (`set obj[%i%]`) do ( \n set cur.%%k=%%l \n) \necho Name = %cur.Name% \necho Value = %cur.ID% \nset /a i = %i%+1 \ngoto loop" }, { "code": null, "e": 29211, "s": 29147, "text": "The following key things need to be noted about the above code." }, { "code": null, "e": 29309, "s": 29211, "text": "Each variable defined using the set command has 2 values associated with each index of the array." }, { "code": null, "e": 29407, "s": 29309, "text": "Each variable defined using the set command has 2 values associated with each index of the array." }, { "code": null, "e": 29517, "s": 29407, "text": "The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3." }, { "code": null, "e": 29627, "s": 29517, "text": "The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3." }, { "code": null, "e": 29754, "s": 29627, "text": "We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code." }, { "code": null, "e": 29881, "s": 29754, "text": "We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code." }, { "code": null, "e": 29962, "s": 29881, "text": "We are able to access each element of the structure using the obj[%i%] notation." }, { "code": null, "e": 30043, "s": 29962, "text": "We are able to access each element of the structure using the obj[%i%] notation." }, { "code": null, "e": 30092, "s": 30043, "text": "The above command produces the following output." }, { "code": null, "e": 30164, "s": 30092, "text": "Name = Joe \nValue = 1 \nName = Mark \nValue = 2 \nName = Mohan \nValue = 3\n" }, { "code": null, "e": 30479, "s": 30164, "text": "Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 30538, "s": 30479, "text": "The first decision-making statement is the ‘if’ statement." }, { "code": null, "e": 30648, "s": 30538, "text": "The next decision making statement is the If/else statement. Following is the general form of this statement." }, { "code": null, "e": 30791, "s": 30648, "text": "Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement." }, { "code": null, "e": 30898, "s": 30791, "text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations." }, { "code": null, "e": 30962, "s": 30898, "text": "In batch script, the following types of operators are possible." }, { "code": null, "e": 30983, "s": 30962, "text": "Arithmetic operators" }, { "code": null, "e": 31004, "s": 30983, "text": "Relational operators" }, { "code": null, "e": 31022, "s": 31004, "text": "Logical operators" }, { "code": null, "e": 31043, "s": 31022, "text": "Assignment operators" }, { "code": null, "e": 31061, "s": 31043, "text": "Bitwise operators" }, { "code": null, "e": 31191, "s": 31061, "text": "Batch script language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available." }, { "code": null, "e": 31204, "s": 31191, "text": "Show Example" }, { "code": null, "e": 31307, "s": 31204, "text": "Relational operators allow of the comparison of objects. Below are the relational operators available." }, { "code": null, "e": 31320, "s": 31307, "text": "Show Example" }, { "code": null, "e": 31427, "s": 31320, "text": "Logical operators are used to evaluate Boolean expressions. Following are the logical operators available." }, { "code": null, "e": 31669, "s": 31427, "text": "The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator." }, { "code": null, "e": 31682, "s": 31669, "text": "Show Example" }, { "code": null, "e": 31790, "s": 31682, "text": "Batch Script language also provides assignment operators. Following are the assignment operators available." }, { "code": null, "e": 31803, "s": 31790, "text": "Show Example" }, { "code": null, "e": 31816, "s": 31803, "text": "Set /A a = 5" }, { "code": null, "e": 31823, "s": 31816, "text": "a += 3" }, { "code": null, "e": 31840, "s": 31823, "text": "Output will be 8" }, { "code": null, "e": 31853, "s": 31840, "text": "Set /A a = 5" }, { "code": null, "e": 31860, "s": 31853, "text": "a -= 3" }, { "code": null, "e": 31877, "s": 31860, "text": "Output will be 2" }, { "code": null, "e": 31890, "s": 31877, "text": "Set /A a = 5" }, { "code": null, "e": 31897, "s": 31890, "text": "a *= 3" }, { "code": null, "e": 31915, "s": 31897, "text": "Output will be 15" }, { "code": null, "e": 31928, "s": 31915, "text": "Set /A a = 6" }, { "code": null, "e": 31935, "s": 31928, "text": "a/ = 3" }, { "code": null, "e": 31952, "s": 31935, "text": "Output will be 2" }, { "code": null, "e": 31965, "s": 31952, "text": "Set /A a = 5" }, { "code": null, "e": 31972, "s": 31965, "text": "a% = 3" }, { "code": null, "e": 31989, "s": 31972, "text": "Output will be 2" }, { "code": null, "e": 32081, "s": 31989, "text": "Bitwise operators are also possible in batch script. Following are the operators available." }, { "code": null, "e": 32094, "s": 32081, "text": "Show Example" }, { "code": null, "e": 32151, "s": 32094, "text": "Following is the truth table showcasing these operators." }, { "code": null, "e": 32272, "s": 32151, "text": "The date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system." }, { "code": null, "e": 32307, "s": 32272, "text": "This command gets the system date." }, { "code": null, "e": 32313, "s": 32307, "text": "DATE\n" }, { "code": null, "e": 32336, "s": 32313, "text": "@echo off \necho %DATE%" }, { "code": null, "e": 32407, "s": 32336, "text": "The current date will be displayed in the command prompt. For example," }, { "code": null, "e": 32423, "s": 32407, "text": "Mon 12/28/2015\n" }, { "code": null, "e": 32463, "s": 32423, "text": "This command sets or displays the time." }, { "code": null, "e": 32469, "s": 32463, "text": "TIME\n" }, { "code": null, "e": 32492, "s": 32469, "text": "@echo off \necho %TIME%" }, { "code": null, "e": 32548, "s": 32492, "text": "The current system time will be displayed. For example," }, { "code": null, "e": 32561, "s": 32548, "text": "22:06:52.87\n" }, { "code": null, "e": 32661, "s": 32561, "text": "Following are some implementations which can be used to get the date and time in different formats." }, { "code": null, "e": 33024, "s": 32661, "text": "@echo off \necho/Today is: %year%-%month%-%day% \ngoto :EOF \nsetlocal ENABLEEXTENSIONS \nset t = 2&if \"%date%z\" LSS \"A\" set t = 1 \n\nfor /f \"skip=1 tokens = 2-4 delims = (-)\" %%a in ('echo/^|date') do ( \n for /f \"tokens = %t%-4 delims=.-/ \" %%d in ('date/t') do ( \n set %%a=%%d&set %%b=%%e&set %%c=%%f)) \nendlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF" }, { "code": null, "e": 33073, "s": 33024, "text": "The above command produces the following output." }, { "code": null, "e": 33095, "s": 33073, "text": "Today is: 2015-12-30\n" }, { "code": null, "e": 33493, "s": 33095, "text": "There are three universal “files” for keyboard input, printing text on the screen and printing errors on the screen. The “Standard In” file, known as stdin, contains the input to the program/script. The “Standard Out” file, known as stdout, is used to write output for display on the screen. Finally, the “Standard Err” file, known as stderr, contains any error messages for display on the screen." }, { "code": null, "e": 33673, "s": 33493, "text": "Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2." }, { "code": null, "e": 33878, "s": 33673, "text": "One common practice in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. The following example shows how this can be done." }, { "code": null, "e": 33898, "s": 33878, "text": "Dir C:\\ > list.txt\n" }, { "code": null, "e": 33990, "s": 33898, "text": "In the above example, the stdout of the command Dir C:\\ is redirected to the file list.txt." }, { "code": null, "e": 34101, "s": 33990, "text": "If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt." }, { "code": null, "e": 34122, "s": 34101, "text": "Dir C:\\ 2> list.txt\n" }, { "code": null, "e": 34240, "s": 34122, "text": "One can even combine the stdout and stderr streams using the file number and the ‘&’ prefix. Following is an example." }, { "code": null, "e": 34266, "s": 34240, "text": "DIR C:\\ > lists.txt 2>&1\n" }, { "code": null, "e": 34438, "s": 34266, "text": "The pseudo file NUL is used to discard any output from a program. The following example shows that the output of the command DIR is discarded by sending the output to NUL." }, { "code": null, "e": 34453, "s": 34438, "text": "Dir C:\\ > NUL\n" }, { "code": null, "e": 34599, "s": 34453, "text": "To work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt’s own stdin, called CON." }, { "code": null, "e": 34867, "s": 34599, "text": "The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt." }, { "code": null, "e": 34889, "s": 34867, "text": "TYPE CON > lists.txt\n" }, { "code": null, "e": 35260, "s": 34889, "text": "By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly." }, { "code": null, "e": 35318, "s": 35260, "text": "Following are the common exit code and their description." }, { "code": null, "e": 35323, "s": 35318, "text": "9009" }, { "code": null, "e": 35330, "s": 35323, "text": "0x2331" }, { "code": null, "e": 35340, "s": 35330, "text": "221225495" }, { "code": null, "e": 35351, "s": 35340, "text": "0xC0000017" }, { "code": null, "e": 35363, "s": 35351, "text": "-1073741801" }, { "code": null, "e": 35403, "s": 35363, "text": "Not enough virtual memory is available." }, { "code": null, "e": 35452, "s": 35403, "text": "It indicates that Windows has run out of memory." }, { "code": null, "e": 35463, "s": 35452, "text": "3221225786" }, { "code": null, "e": 35474, "s": 35463, "text": "0xC000013A" }, { "code": null, "e": 35486, "s": 35474, "text": "-1073741510" }, { "code": null, "e": 35497, "s": 35486, "text": "3221225794" }, { "code": null, "e": 35508, "s": 35497, "text": "0xC0000142" }, { "code": null, "e": 35520, "s": 35508, "text": "-1073741502" }, { "code": null, "e": 35625, "s": 35520, "text": "The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script." }, { "code": null, "e": 35700, "s": 35625, "text": "By default, the way to check for the ERRORLEVEL is via the following code." }, { "code": null, "e": 35745, "s": 35700, "text": "IF %ERRORLEVEL% NEQ 0 ( \n DO_Something \n)\n" }, { "code": null, "e": 35874, "s": 35745, "text": "It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file." }, { "code": null, "e": 35948, "s": 35874, "text": "EXIT /B at the end of the batch file will stop execution of a batch file." }, { "code": null, "e": 36034, "s": 35948, "text": "Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes." }, { "code": null, "e": 36368, "s": 36034, "text": "Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers." }, { "code": null, "e": 36449, "s": 36368, "text": "Let’s look at a quick example on how to check for error codes from a batch file." }, { "code": null, "e": 36767, "s": 36449, "text": "Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9." }, { "code": null, "e": 36843, "s": 36767, "text": "if not exist c:\\lists.txt exit 7 \nif not defined userprofile exit 9 \nexit 0" }, { "code": null, "e": 37163, "s": 36843, "text": "Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0." }, { "code": null, "e": 37233, "s": 37163, "text": "Call Find.cmd\n\nif errorlevel gtr 0 exit \necho “Successful completion”" }, { "code": null, "e": 37307, "s": 37233, "text": "In the above program, we can have the following scenarios as the output −" }, { "code": null, "e": 37402, "s": 37307, "text": "If the file c:\\lists.txt does not exist, then nothing will be displayed in the console output." }, { "code": null, "e": 37497, "s": 37402, "text": "If the file c:\\lists.txt does not exist, then nothing will be displayed in the console output." }, { "code": null, "e": 37595, "s": 37497, "text": "If the variable userprofile does not exist, then nothing will be displayed in the console output." }, { "code": null, "e": 37693, "s": 37595, "text": "If the variable userprofile does not exist, then nothing will be displayed in the console output." }, { "code": null, "e": 37812, "s": 37693, "text": "If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt." }, { "code": null, "e": 37931, "s": 37812, "text": "If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt." }, { "code": null, "e": 38228, "s": 37931, "text": "In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements." }, { "code": null, "e": 38384, "s": 38228, "text": "There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels." }, { "code": null, "e": 38541, "s": 38384, "text": "The \"FOR\" construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values." }, { "code": null, "e": 38665, "s": 38541, "text": "The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement." }, { "code": null, "e": 38756, "s": 38665, "text": "Following is the classic ‘for’ statement which is available in most programming languages." }, { "code": null, "e": 38938, "s": 38756, "text": "The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments." }, { "code": null, "e": 39043, "s": 38938, "text": "@ECHO OFF \n:Loop \n\nIF \"%1\"==\"\" GOTO completed \nFOR %%F IN (%1) DO echo %%F \nSHIFT \nGOTO Loop \n:completed" }, { "code": null, "e": 39249, "s": 39043, "text": "Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3." }, { "code": null, "e": 39258, "s": 39249, "text": "1 \n2 \n3\n" }, { "code": null, "e": 39496, "s": 39258, "text": "The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop." }, { "code": null, "e": 39682, "s": 39496, "text": "A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function." }, { "code": null, "e": 39766, "s": 39682, "text": "As like any other languages, functions in Batch Script follows the same procedure −" }, { "code": null, "e": 39865, "s": 39766, "text": "Function Declaration − It tells the compiler about a function's name, return type, and parameters." }, { "code": null, "e": 39964, "s": 39865, "text": "Function Declaration − It tells the compiler about a function's name, return type, and parameters." }, { "code": null, "e": 40031, "s": 39964, "text": "Function Definition − It provides the actual body of the function." }, { "code": null, "e": 40098, "s": 40031, "text": "Function Definition − It provides the actual body of the function." }, { "code": null, "e": 40382, "s": 40098, "text": "In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input 'parameters' to the function, process the functions in the main body, and pass back the values to the functions as output 'return types'." }, { "code": null, "e": 40629, "s": 40382, "text": "Every function has a function name, which describes the task that the function performs. To use a function, you \"call\" that function with its name and pass its input values (known as arguments) that matches the types of the function's parameters." }, { "code": null, "e": 40675, "s": 40629, "text": "Following is the syntax of a simple function." }, { "code": null, "e": 40716, "s": 40675, "text": ":function_name \nDo_something \nEXIT /B 0\n" }, { "code": null, "e": 40841, "s": 40716, "text": "The function_name is the name given to the function which should have some meaning to match what the function actually does." }, { "code": null, "e": 40966, "s": 40841, "text": "The function_name is the name given to the function which should have some meaning to match what the function actually does." }, { "code": null, "e": 41037, "s": 40966, "text": "The EXIT statement is used to ensure that the function exits properly." }, { "code": null, "e": 41108, "s": 41037, "text": "The EXIT statement is used to ensure that the function exits properly." }, { "code": null, "e": 41154, "s": 41108, "text": "Following is an example of a simple function." }, { "code": null, "e": 41226, "s": 41154, "text": ":Display \nSET /A index=2 \necho The value of index is %index% \nEXIT /B 0" }, { "code": null, "e": 41290, "s": 41226, "text": "A function is called in Batch Script by using the call command." }, { "code": null, "e": 41385, "s": 41290, "text": "Functions can work with parameters by simply passing them when a call is made to the function." }, { "code": null, "e": 41457, "s": 41385, "text": "Functions can work with return values by simply passing variables names" }, { "code": null, "e": 41571, "s": 41457, "text": "Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function." }, { "code": null, "e": 41711, "s": 41571, "text": "The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller." }, { "code": null, "e": 41837, "s": 41711, "text": "In Batch Script, it is possible to perform the normal file I/O operations that would be expected in any programming language." }, { "code": null, "e": 41973, "s": 41837, "text": "The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file." }, { "code": null, "e": 42112, "s": 41973, "text": "Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file." }, { "code": null, "e": 42257, "s": 42112, "text": "Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file." }, { "code": null, "e": 42407, "s": 42257, "text": "Reading of files in a batch script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read." }, { "code": null, "e": 42466, "s": 42407, "text": "For deleting files, Batch Script provides the DEL command." }, { "code": null, "e": 42535, "s": 42466, "text": "For renaming files, Batch Script provides the REN or RENAME command." }, { "code": null, "e": 42593, "s": 42535, "text": "For moving files, Batch Script provides the MOVE command." }, { "code": null, "e": 42738, "s": 42593, "text": "The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command." }, { "code": null, "e": 42889, "s": 42738, "text": "When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing." }, { "code": null, "e": 43026, "s": 42889, "text": "One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation." }, { "code": null, "e": 43156, "s": 43026, "text": "In Batch Script, it is possible to perform the normal folder based operations that would be expected in any programming language." }, { "code": null, "e": 43245, "s": 43156, "text": "The creation of a folder is done with the assistance of the MD (Make directory) command." }, { "code": null, "e": 43403, "s": 43245, "text": "The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory." }, { "code": null, "e": 43467, "s": 43403, "text": "For deleting folders, Batch Scripting provides the DEL command." }, { "code": null, "e": 43538, "s": 43467, "text": "For renaming folders, Batch Script provides the REN or RENAME command." }, { "code": null, "e": 43598, "s": 43538, "text": "For moving folders, Batch Script provides the MOVE command." }, { "code": null, "e": 43679, "s": 43598, "text": "In this chapter, we will discuss the various processes involved in Batch Script." }, { "code": null, "e": 43793, "s": 43679, "text": "In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system." }, { "code": null, "e": 43903, "s": 43793, "text": "TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter]\n[/FO format] [/NH]\n" }, { "code": null, "e": 43913, "s": 43903, "text": "/S system" }, { "code": null, "e": 43955, "s": 43913, "text": "Specifies the remote system to connect to" }, { "code": null, "e": 43958, "s": 43955, "text": "/U" }, { "code": null, "e": 43972, "s": 43958, "text": "[domain\\]user" }, { "code": null, "e": 44039, "s": 43972, "text": "Specifies the user context under which the command should execute." }, { "code": null, "e": 44053, "s": 44039, "text": "/P [password]" }, { "code": null, "e": 44134, "s": 44053, "text": "Specifies the password for the given user context. Prompts for input if omitted." }, { "code": null, "e": 44146, "s": 44134, "text": "/M [module]" }, { "code": null, "e": 44272, "s": 44146, "text": "Lists all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed." }, { "code": null, "e": 44277, "s": 44272, "text": "/SVC" }, { "code": null, "e": 44319, "s": 44277, "text": "Displays services hosted in each process." }, { "code": null, "e": 44322, "s": 44319, "text": "/V" }, { "code": null, "e": 44357, "s": 44322, "text": "Displays verbose task information." }, { "code": null, "e": 44368, "s": 44357, "text": "/FI filter" }, { "code": null, "e": 44445, "s": 44368, "text": "Displays a set of tasks that match a given criteria specified by the filter." }, { "code": null, "e": 44456, "s": 44445, "text": "/FO format" }, { "code": null, "e": 44523, "s": 44456, "text": "Specifies the output format. Valid values: \"TABLE\", \"LIST\", \"CSV\"." }, { "code": null, "e": 44527, "s": 44523, "text": "/NH" }, { "code": null, "e": 44635, "s": 44527, "text": "Specifies that the \"Column Header\" should not show in the output. Valid only for \"TABLE\" and \"CSV\" formats." }, { "code": null, "e": 44645, "s": 44635, "text": "TASKLIST\n" }, { "code": null, "e": 44983, "s": 44645, "text": "The above command will get the list of all the processes running on your local system. Following is a snapshot of the output which is rendered when the above command is run as it is. As you can see from the following output, not only do you get the various processes running on your system, you also get the memory usage of each process." }, { "code": null, "e": 47146, "s": 44983, "text": "Image Name PID Session Name Session# Mem Usage\n========================= ======== ================ =========== ============\nSystem Idle Process 0 Services 0 4 K\nSystem 4 Services 0 272 K\nsmss.exe 344 Services 0 1,040 K\ncsrss.exe 528 Services 0 3,892 K\ncsrss.exe 612 Console 1 41,788 K\nwininit.exe 620 Services 0 3,528 K\nwinlogon.exe 648 Console 1 5,884 K\nservices.exe 712 Services 0 6,224 K\nlsass.exe 720 Services 0 9,712 K\nsvchost.exe 788 Services 0 10,048 K\nsvchost.exe 832 Services 0 7,696 K\ndwm.exe 916 Console 1 117,440 K\nnvvsvc.exe 932 Services 0 6,692 K\nnvxdsync.exe 968 Console 1 16,328 K\nnvvsvc.exe 976 Console 1 12,756 K\nsvchost.exe 1012 Services 0 21,648 K\nsvchost.exe 236 Services 0 33,864 K\nsvchost.exe 480 Services 0 11,152 K\nsvchost.exe 1028 Services 0 11,104 K\nsvchost.exe 1048 Services 0 16,108 K\nwlanext.exe 1220 Services 0 12,560 K\nconhost.exe 1228 Services 0 2,588 K\nsvchost.exe 1276 Services 0 13,888 K\nsvchost.exe 1420 Services 0 13,488 K\nspoolsv.exe 1556 Services 0 9,340 K\n" }, { "code": null, "e": 47170, "s": 47146, "text": "tasklist > process.txt\n" }, { "code": null, "e": 47265, "s": 47170, "text": "The above command takes the output displayed by tasklist and saves it to the process.txt file." }, { "code": null, "e": 47299, "s": 47265, "text": "tasklist /fi \"memusage gt 40000\"\n" }, { "code": null, "e": 47435, "s": 47299, "text": "The above command will only fetch those processes whose memory is greater than 40MB. Following is a sample output that can be rendered." }, { "code": null, "e": 48374, "s": 47435, "text": "Image Name PID Session Name Session# Mem Usage\n========================= ======== ================ =========== ============\ndwm.exe 916 Console 1 127,912 K\nexplorer.exe 2904 Console 1 125,868 K\nServerManager.exe 1836 Console 1 59,796 K\nWINWORD.EXE 2456 Console 1 144,504 K\nchrome.exe 4892 Console 1 123,232 K\nchrome.exe 4976 Console 1 69,412 K\nchrome.exe 1724 Console 1 76,416 K\nchrome.exe 3992 Console 1 56,156 K\nchrome.exe 1168 Console 1 233,628 K\nchrome.exe 816 Console 1 66,808 K\n" }, { "code": null, "e": 48590, "s": 48374, "text": "Allows a user running Microsoft Windows XP professional, Windows 2003, or later to kill a task from a Windows command line by process id (PID) or image name. The command used for this purpose is the TASKILL command." }, { "code": null, "e": 48703, "s": 48590, "text": "TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] \n[/PID processid | /IM imagename] } [/T] [/F]\n" }, { "code": null, "e": 48713, "s": 48703, "text": "/S system" }, { "code": null, "e": 48755, "s": 48713, "text": "Specifies the remote system to connect to" }, { "code": null, "e": 48758, "s": 48755, "text": "/U" }, { "code": null, "e": 48772, "s": 48758, "text": "[domain\\]user" }, { "code": null, "e": 48839, "s": 48772, "text": "Specifies the user context under which the command should execute." }, { "code": null, "e": 48853, "s": 48839, "text": "/P [password]" }, { "code": null, "e": 48934, "s": 48853, "text": "Specifies the password for the given user context. Prompts for input if omitted." }, { "code": null, "e": 48938, "s": 48934, "text": "/FI" }, { "code": null, "e": 48949, "s": 48938, "text": "FilterName" }, { "code": null, "e": 49097, "s": 48949, "text": "Applies a filter to select a set of tasks. Allows \"*\" to be used. ex. imagename eq acme* See below filters for additional information and examples." }, { "code": null, "e": 49102, "s": 49097, "text": "/PID" }, { "code": null, "e": 49112, "s": 49102, "text": "processID" }, { "code": null, "e": 49192, "s": 49112, "text": "Specifies the PID of the process to be terminated. Use TaskList to get the PID." }, { "code": null, "e": 49196, "s": 49192, "text": "/IM" }, { "code": null, "e": 49206, "s": 49196, "text": "ImageName" }, { "code": null, "e": 49326, "s": 49206, "text": "Specifies the image name of the process to be terminated. Wildcard '*' can be used to specify all tasks or image names." }, { "code": null, "e": 49329, "s": 49326, "text": "/T" }, { "code": null, "e": 49412, "s": 49329, "text": "Terminates the specified process and any child processes which were started by it." }, { "code": null, "e": 49415, "s": 49412, "text": "/F" }, { "code": null, "e": 49466, "s": 49415, "text": "Specifies to forcefully terminate the process(es)." }, { "code": null, "e": 49495, "s": 49466, "text": "taskkill /f /im notepad.exe\n" }, { "code": null, "e": 49551, "s": 49495, "text": "The above command kills the open notepad task, if open." }, { "code": null, "e": 49570, "s": 49551, "text": "taskill /pid 9214\n" }, { "code": null, "e": 49633, "s": 49570, "text": "The above command kills a process which has a process of 9214." }, { "code": null, "e": 49753, "s": 49633, "text": "DOS scripting also has the availability to start a new process altogether. This is achieved by using the START command." }, { "code": null, "e": 49811, "s": 49753, "text": "START \"title\" [/D path] [options] \"command\" [parameters]\n" }, { "code": null, "e": 49819, "s": 49811, "text": "Wherein" }, { "code": null, "e": 49873, "s": 49819, "text": "title − Text for the CMD window title bar (required.)" }, { "code": null, "e": 49927, "s": 49873, "text": "title − Text for the CMD window title bar (required.)" }, { "code": null, "e": 49954, "s": 49927, "text": "path − Starting directory." }, { "code": null, "e": 49981, "s": 49954, "text": "path − Starting directory." }, { "code": null, "e": 50045, "s": 49981, "text": "command − The command, batch file or executable program to run." }, { "code": null, "e": 50109, "s": 50045, "text": "command − The command, batch file or executable program to run." }, { "code": null, "e": 50160, "s": 50109, "text": "parameters − The parameters passed to the command." }, { "code": null, "e": 50211, "s": 50160, "text": "parameters − The parameters passed to the command." }, { "code": null, "e": 50216, "s": 50211, "text": "/MIN" }, { "code": null, "e": 50239, "s": 50216, "text": "Start window Minimized" }, { "code": null, "e": 50244, "s": 50239, "text": "/MAX" }, { "code": null, "e": 50268, "s": 50244, "text": "Start window maximized." }, { "code": null, "e": 50273, "s": 50268, "text": "/LOW" }, { "code": null, "e": 50298, "s": 50273, "text": "Use IDLE priority class." }, { "code": null, "e": 50306, "s": 50298, "text": "/NORMAL" }, { "code": null, "e": 50333, "s": 50306, "text": "Use NORMAL priority class." }, { "code": null, "e": 50346, "s": 50333, "text": "/ABOVENORMAL" }, { "code": null, "e": 50378, "s": 50346, "text": "Use ABOVENORMAL priority class." }, { "code": null, "e": 50391, "s": 50378, "text": "/BELOWNORMAL" }, { "code": null, "e": 50423, "s": 50391, "text": "Use BELOWNORMAL priority class." }, { "code": null, "e": 50429, "s": 50423, "text": "/HIGH" }, { "code": null, "e": 50454, "s": 50429, "text": "Use HIGH priority class." }, { "code": null, "e": 50464, "s": 50454, "text": "/REALTIME" }, { "code": null, "e": 50493, "s": 50464, "text": "Use REALTIME priority class." }, { "code": null, "e": 50534, "s": 50493, "text": "START \"Test Batch Script\" /Min test.bat\n" }, { "code": null, "e": 50697, "s": 50534, "text": "The above command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”." }, { "code": null, "e": 50775, "s": 50697, "text": "START \"\" \"C:\\Program Files\\Microsoft Office\\Winword.exe\" \"D:\\test\\TESTA.txt\"\n" }, { "code": null, "e": 50890, "s": 50775, "text": "The above command will actually run Microsoft word in another process and then open the file TESTA.txt in MS Word." }, { "code": null, "e": 51143, "s": 50890, "text": "Aliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing." }, { "code": null, "e": 51151, "s": 51143, "text": "Dir /w\n" }, { "code": null, "e": 51219, "s": 51151, "text": "Suppose if we were to create a shortcut to this command as follows." }, { "code": null, "e": 51232, "s": 51219, "text": "dw = dir /w\n" }, { "code": null, "e": 51372, "s": 51232, "text": "When we want to execute the dir /w command, we can simply type in the word dw. The word ‘dw’ has now become an alias to the command Dir /w." }, { "code": null, "e": 51419, "s": 51372, "text": "Alias are managed by using the doskey command." }, { "code": null, "e": 51456, "s": 51419, "text": "DOSKEY [options] [macroname=[text]]\n" }, { "code": null, "e": 51464, "s": 51456, "text": "Wherein" }, { "code": null, "e": 51504, "s": 51464, "text": "macroname − A short name for the macro." }, { "code": null, "e": 51544, "s": 51504, "text": "macroname − A short name for the macro." }, { "code": null, "e": 51584, "s": 51544, "text": "text − The commands you want to recall." }, { "code": null, "e": 51624, "s": 51584, "text": "text − The commands you want to recall." }, { "code": null, "e": 51715, "s": 51624, "text": "Following are the description of the options which can be presented to the DOSKEY command." }, { "code": null, "e": 51726, "s": 51715, "text": "/REINSTALL" }, { "code": null, "e": 51756, "s": 51726, "text": "Installs a new copy of Doskey" }, { "code": null, "e": 51773, "s": 51756, "text": "/LISTSIZE = size" }, { "code": null, "e": 51810, "s": 51773, "text": "Sets size of command history buffer." }, { "code": null, "e": 51818, "s": 51810, "text": "/MACROS" }, { "code": null, "e": 51846, "s": 51818, "text": "Displays all Doskey macros." }, { "code": null, "e": 51858, "s": 51846, "text": "/MACROS:ALL" }, { "code": null, "e": 51931, "s": 51858, "text": "Displays all Doskey macros for all executables which have Doskey macros." }, { "code": null, "e": 51947, "s": 51931, "text": "/MACROS:exename" }, { "code": null, "e": 52000, "s": 51947, "text": "Displays all Doskey macros for the given executable." }, { "code": null, "e": 52009, "s": 52000, "text": "/HISTORY" }, { "code": null, "e": 52049, "s": 52009, "text": "Displays all commands stored in memory." }, { "code": null, "e": 52057, "s": 52049, "text": "/INSERT" }, { "code": null, "e": 52115, "s": 52057, "text": "Specifies that new text you type is inserted in old text." }, { "code": null, "e": 52127, "s": 52115, "text": "/OVERSTRIKE" }, { "code": null, "e": 52172, "s": 52127, "text": "Specifies that new text overwrites old text." }, { "code": null, "e": 52191, "s": 52172, "text": "/EXENAME = exename" }, { "code": null, "e": 52217, "s": 52191, "text": "Specifies the executable." }, { "code": null, "e": 52239, "s": 52217, "text": "/MACROFILE = filename" }, { "code": null, "e": 52278, "s": 52239, "text": "Specifies a file of macros to install." }, { "code": null, "e": 52288, "s": 52278, "text": "macroname" }, { "code": null, "e": 52329, "s": 52288, "text": "Specifies a name for a macro you create." }, { "code": null, "e": 52334, "s": 52329, "text": "text" }, { "code": null, "e": 52373, "s": 52334, "text": "Specifies commands you want to record." }, { "code": null, "e": 52613, "s": 52373, "text": "Create a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command." }, { "code": null, "e": 52659, "s": 52613, "text": "@echo off\ndoskey cd = cd/test\ndoskey d = dir\n" }, { "code": null, "e": 52747, "s": 52659, "text": "Once you execute the command, you will able to run these aliases in the command prompt." }, { "code": null, "e": 52957, "s": 52747, "text": "The following screenshot shows that after the above created batch file is executed, you can freely enter the ‘d’ command and it will give you the directory listing which means that your alias has been created." }, { "code": null, "e": 53033, "s": 52957, "text": "An alias or macro can be deleted by setting the value of the macro to NULL." }, { "code": null, "e": 53083, "s": 53033, "text": "@echo off\ndoskey cd = cd/test\ndoskey d = dir\nd= \n" }, { "code": null, "e": 53259, "s": 53083, "text": "In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted." }, { "code": null, "e": 53353, "s": 53259, "text": "An alias or macro can be replaced by setting the value of the macro to the new desired value." }, { "code": null, "e": 53411, "s": 53353, "text": "@echo off\ndoskey cd = cd/test\ndoskey d = dir\n\nd = dir /w\n" }, { "code": null, "e": 53614, "s": 53411, "text": "In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value." }, { "code": null, "e": 53783, "s": 53614, "text": "Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe." }, { "code": null, "e": 54214, "s": 53783, "text": "Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers." }, { "code": null, "e": 54388, "s": 54214, "text": "Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) −" }, { "code": null, "e": 54519, "s": 54388, "text": "Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings." }, { "code": null, "e": 54650, "s": 54519, "text": "Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings." }, { "code": null, "e": 54672, "s": 54650, "text": "Device setup classes." }, { "code": null, "e": 54694, "s": 54672, "text": "Device setup classes." }, { "code": null, "e": 54731, "s": 54694, "text": "The devices in a device setup class." }, { "code": null, "e": 54768, "s": 54731, "text": "The devices in a device setup class." }, { "code": null, "e": 54803, "s": 54768, "text": "INF files and device driver files." }, { "code": null, "e": 54838, "s": 54803, "text": "INF files and device driver files." }, { "code": null, "e": 54866, "s": 54838, "text": "Details of driver packages." }, { "code": null, "e": 54894, "s": 54866, "text": "Details of driver packages." }, { "code": null, "e": 54914, "s": 54894, "text": "Hardware resources." }, { "code": null, "e": 54934, "s": 54914, "text": "Hardware resources." }, { "code": null, "e": 54949, "s": 54934, "text": "Device status." }, { "code": null, "e": 54964, "s": 54949, "text": "Device status." }, { "code": null, "e": 54987, "s": 54964, "text": "Expected driver stack." }, { "code": null, "e": 55010, "s": 54987, "text": "Expected driver stack." }, { "code": null, "e": 55059, "s": 55010, "text": "Third-party driver packages in the driver store." }, { "code": null, "e": 55108, "s": 55059, "text": "Third-party driver packages in the driver store." }, { "code": null, "e": 55272, "s": 55108, "text": "Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class." }, { "code": null, "e": 55436, "s": 55272, "text": "Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class." }, { "code": null, "e": 56032, "s": 55436, "text": "Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −\n\nEnable a device.\nDisable a device.\nUpdate drivers (interactive and non-interactive).\nInstall a device (create a devnode and install software).\nRemove a device from the device tree and delete its device stack.\nRescan for Plug and Play devices.\nAdd, delete, and reorder the hardware IDs of root-enumerated devices.\nChange the upper and lower filter drivers for a device setup class.\nAdd and delete third-party driver packages from the driver store.\n\n" }, { "code": null, "e": 56178, "s": 56032, "text": "Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −" }, { "code": null, "e": 56195, "s": 56178, "text": "Enable a device." }, { "code": null, "e": 56212, "s": 56195, "text": "Enable a device." }, { "code": null, "e": 56230, "s": 56212, "text": "Disable a device." }, { "code": null, "e": 56248, "s": 56230, "text": "Disable a device." }, { "code": null, "e": 56298, "s": 56248, "text": "Update drivers (interactive and non-interactive)." }, { "code": null, "e": 56348, "s": 56298, "text": "Update drivers (interactive and non-interactive)." }, { "code": null, "e": 56406, "s": 56348, "text": "Install a device (create a devnode and install software)." }, { "code": null, "e": 56464, "s": 56406, "text": "Install a device (create a devnode and install software)." }, { "code": null, "e": 56530, "s": 56464, "text": "Remove a device from the device tree and delete its device stack." }, { "code": null, "e": 56596, "s": 56530, "text": "Remove a device from the device tree and delete its device stack." }, { "code": null, "e": 56630, "s": 56596, "text": "Rescan for Plug and Play devices." }, { "code": null, "e": 56664, "s": 56630, "text": "Rescan for Plug and Play devices." }, { "code": null, "e": 56734, "s": 56664, "text": "Add, delete, and reorder the hardware IDs of root-enumerated devices." }, { "code": null, "e": 56804, "s": 56734, "text": "Add, delete, and reorder the hardware IDs of root-enumerated devices." }, { "code": null, "e": 56872, "s": 56804, "text": "Change the upper and lower filter drivers for a device setup class." }, { "code": null, "e": 56940, "s": 56872, "text": "Change the upper and lower filter drivers for a device setup class." }, { "code": null, "e": 57006, "s": 56940, "text": "Add and delete third-party driver packages from the driver store." }, { "code": null, "e": 57072, "s": 57006, "text": "Add and delete third-party driver packages from the driver store." }, { "code": null, "e": 57254, "s": 57072, "text": "DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed." }, { "code": null, "e": 57366, "s": 57254, "text": "%WindowsSdkDir%\\tools\\x64\\devcon.exe\n%WindowsSdkDir%\\tools\\x86\\devcon.exe\n%WindowsSdkDir%\\tools\\arm\\devcon.exe\n" }, { "code": null, "e": 57415, "s": 57366, "text": "devcon [/m:\\\\computer] [/r] command [arguments]\n" }, { "code": null, "e": 57423, "s": 57415, "text": "wherein" }, { "code": null, "e": 57520, "s": 57423, "text": "/m:\\\\computer − Runs the command on the specified remote computer. The backslashes are required." }, { "code": null, "e": 57617, "s": 57520, "text": "/m:\\\\computer − Runs the command on the specified remote computer. The backslashes are required." }, { "code": null, "e": 57748, "s": 57617, "text": "/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective." }, { "code": null, "e": 57879, "s": 57748, "text": "/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective." }, { "code": null, "e": 57917, "s": 57879, "text": "command − Specifies a DevCon command." }, { "code": null, "e": 57955, "s": 57917, "text": "command − Specifies a DevCon command." }, { "code": null, "e": 58192, "s": 57955, "text": "To list and display information about devices on the computer, use the following commands −\n\nDevCon HwIDs\nDevCon Classes\nDevCon ListClass\nDevCon DriverFiles\nDevCon DriverNodes\nDevCon Resources\nDevCon Stack\nDevCon Status\nDevCon Dp_enum\n\n" }, { "code": null, "e": 58284, "s": 58192, "text": "To list and display information about devices on the computer, use the following commands −" }, { "code": null, "e": 58297, "s": 58284, "text": "DevCon HwIDs" }, { "code": null, "e": 58310, "s": 58297, "text": "DevCon HwIDs" }, { "code": null, "e": 58325, "s": 58310, "text": "DevCon Classes" }, { "code": null, "e": 58340, "s": 58325, "text": "DevCon Classes" }, { "code": null, "e": 58357, "s": 58340, "text": "DevCon ListClass" }, { "code": null, "e": 58374, "s": 58357, "text": "DevCon ListClass" }, { "code": null, "e": 58393, "s": 58374, "text": "DevCon DriverFiles" }, { "code": null, "e": 58412, "s": 58393, "text": "DevCon DriverFiles" }, { "code": null, "e": 58431, "s": 58412, "text": "DevCon DriverNodes" }, { "code": null, "e": 58450, "s": 58431, "text": "DevCon DriverNodes" }, { "code": null, "e": 58467, "s": 58450, "text": "DevCon Resources" }, { "code": null, "e": 58484, "s": 58467, "text": "DevCon Resources" }, { "code": null, "e": 58497, "s": 58484, "text": "DevCon Stack" }, { "code": null, "e": 58510, "s": 58497, "text": "DevCon Stack" }, { "code": null, "e": 58524, "s": 58510, "text": "DevCon Status" }, { "code": null, "e": 58538, "s": 58524, "text": "DevCon Status" }, { "code": null, "e": 58553, "s": 58538, "text": "DevCon Dp_enum" }, { "code": null, "e": 58568, "s": 58553, "text": "DevCon Dp_enum" }, { "code": null, "e": 58684, "s": 58568, "text": "To search for information about devices on the computer, use the following commands −\n\nDevCon Find\nDevCon FindAll\n\n" }, { "code": null, "e": 58770, "s": 58684, "text": "To search for information about devices on the computer, use the following commands −" }, { "code": null, "e": 58782, "s": 58770, "text": "DevCon Find" }, { "code": null, "e": 58794, "s": 58782, "text": "DevCon Find" }, { "code": null, "e": 58809, "s": 58794, "text": "DevCon FindAll" }, { "code": null, "e": 58824, "s": 58809, "text": "DevCon FindAll" }, { "code": null, "e": 59106, "s": 58824, "text": "To manipulate the device or change its configuration, use the following commands −\n\nDevCon Enable\nDevCon Disable\nDevCon Update\nDevCon UpdateNI\nDevCon Install\nDevCon Remove\nDevCon Rescan\nDevCon Restart\nDevCon Reboot\nDevCon SetHwID\nDevCon ClassFilter\nDevCon Dp_add\nDevCon Dp_delete\n\n" }, { "code": null, "e": 59189, "s": 59106, "text": "To manipulate the device or change its configuration, use the following commands −" }, { "code": null, "e": 59203, "s": 59189, "text": "DevCon Enable" }, { "code": null, "e": 59217, "s": 59203, "text": "DevCon Enable" }, { "code": null, "e": 59232, "s": 59217, "text": "DevCon Disable" }, { "code": null, "e": 59247, "s": 59232, "text": "DevCon Disable" }, { "code": null, "e": 59261, "s": 59247, "text": "DevCon Update" }, { "code": null, "e": 59275, "s": 59261, "text": "DevCon Update" }, { "code": null, "e": 59291, "s": 59275, "text": "DevCon UpdateNI" }, { "code": null, "e": 59307, "s": 59291, "text": "DevCon UpdateNI" }, { "code": null, "e": 59322, "s": 59307, "text": "DevCon Install" }, { "code": null, "e": 59337, "s": 59322, "text": "DevCon Install" }, { "code": null, "e": 59351, "s": 59337, "text": "DevCon Remove" }, { "code": null, "e": 59365, "s": 59351, "text": "DevCon Remove" }, { "code": null, "e": 59379, "s": 59365, "text": "DevCon Rescan" }, { "code": null, "e": 59393, "s": 59379, "text": "DevCon Rescan" }, { "code": null, "e": 59408, "s": 59393, "text": "DevCon Restart" }, { "code": null, "e": 59423, "s": 59408, "text": "DevCon Restart" }, { "code": null, "e": 59437, "s": 59423, "text": "DevCon Reboot" }, { "code": null, "e": 59451, "s": 59437, "text": "DevCon Reboot" }, { "code": null, "e": 59466, "s": 59451, "text": "DevCon SetHwID" }, { "code": null, "e": 59481, "s": 59466, "text": "DevCon SetHwID" }, { "code": null, "e": 59500, "s": 59481, "text": "DevCon ClassFilter" }, { "code": null, "e": 59519, "s": 59500, "text": "DevCon ClassFilter" }, { "code": null, "e": 59533, "s": 59519, "text": "DevCon Dp_add" }, { "code": null, "e": 59547, "s": 59533, "text": "DevCon Dp_add" }, { "code": null, "e": 59564, "s": 59547, "text": "DevCon Dp_delete" }, { "code": null, "e": 59581, "s": 59564, "text": "DevCon Dp_delete" }, { "code": null, "e": 59644, "s": 59581, "text": "Following are some examples on how the DevCon command is used." }, { "code": null, "e": 59667, "s": 59644, "text": "List all driver files\n" }, { "code": null, "e": 60017, "s": 59667, "text": "The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt." }, { "code": null, "e": 60057, "s": 60017, "text": "devcon driverfiles * > driverfiles.txt\n" }, { "code": null, "e": 60396, "s": 60057, "text": "The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file." }, { "code": null, "e": 60426, "s": 60396, "text": "devcon status * > status.txt\n" }, { "code": null, "e": 60673, "s": 60426, "text": "The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective." }, { "code": null, "e": 60701, "s": 60673, "text": "devcon /r enable = Printer\n" }, { "code": null, "e": 60920, "s": 60701, "text": "The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b)." }, { "code": null, "e": 60976, "s": 60920, "text": "devcon /r install c:\\windows\\inf\\keyboard.inf *PNP030b\n" }, { "code": null, "e": 61038, "s": 60976, "text": "The following command will scan the computer for new devices." }, { "code": null, "e": 61051, "s": 61038, "text": "devcon scan\n" }, { "code": null, "e": 61115, "s": 61051, "text": "The following command will rescan the computer for new devices." }, { "code": null, "e": 61130, "s": 61115, "text": "devcon rescan\n" }, { "code": null, "e": 61376, "s": 61130, "text": "The Registry is one of the key elements on a windows system. It contains a lot of information on various aspects of the operating system. Almost all applications installed on a windows system interact with the registry in some form or the other." }, { "code": null, "e": 61709, "s": 61376, "text": "The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows' path names, using backslashes to indicate levels of hierarchy." }, { "code": null, "e": 61829, "s": 61709, "text": "This chapter looks at various functions such as querying values, adding, deleting and editing values from the registry." }, { "code": null, "e": 61890, "s": 61829, "text": "Reading from the registry is done via the REG QUERY command." }, { "code": null, "e": 61946, "s": 61890, "text": "Adding to the registry is done via the REG ADD command." }, { "code": null, "e": 62006, "s": 61946, "text": "Deleting from the registry is done via the REG DEL command." }, { "code": null, "e": 62066, "s": 62006, "text": "Copying from the registry is done via the REG COPY command." }, { "code": null, "e": 62127, "s": 62066, "text": "Comparing registry keys is done via the REG COMPARE command." }, { "code": null, "e": 62344, "s": 62127, "text": "Batch script has the facility to work with network settings. The NET command is used to update, fix, or view the network or network settings. This chapter looks at the different options available for the net command." }, { "code": null, "e": 62409, "s": 62344, "text": "View the current password & logon restrictions for the computer." }, { "code": null, "e": 62461, "s": 62409, "text": "Displays your current server or workgroup settings." }, { "code": null, "e": 62531, "s": 62461, "text": "Adds or removes a computer attached to the windows domain controller." }, { "code": null, "e": 62574, "s": 62531, "text": "This command can be used for the following" }, { "code": null, "e": 62621, "s": 62574, "text": "View the details of a particular user account." }, { "code": null, "e": 62682, "s": 62621, "text": "This command is used to stop and start a particular service." }, { "code": null, "e": 62739, "s": 62682, "text": "Display network statistics of the workstation or server." }, { "code": null, "e": 62848, "s": 62739, "text": "Connects or disconnects your computer from a shared resource or displays information about your connections." }, { "code": null, "e": 62932, "s": 62848, "text": "Printing can also be controlled from within Batch Script via the NET PRINT command." }, { "code": null, "e": 62981, "s": 62932, "text": "PRINT [/D:device] [[drive:][path]filename[...]]\n" }, { "code": null, "e": 63025, "s": 62981, "text": "Where /D:device - Specifies a print device." }, { "code": null, "e": 63057, "s": 63025, "text": "print c:\\example.txt /c /d:lpt1" }, { "code": null, "e": 63134, "s": 63057, "text": "The above command will print the example.txt file to the parallel port lpt1." }, { "code": null, "e": 63271, "s": 63134, "text": "As of Windows 2000, many, but not all, printer settings can be configured from Windows's command line using PRINTUI.DLL and RUNDLL32.EXE" }, { "code": null, "e": 63339, "s": 63271, "text": "RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ]\n" }, { "code": null, "e": 63395, "s": 63339, "text": "Where some of the options available are the following −" }, { "code": null, "e": 63423, "s": 63395, "text": "/dl − Delete local printer." }, { "code": null, "e": 63451, "s": 63423, "text": "/dl − Delete local printer." }, { "code": null, "e": 63492, "s": 63451, "text": "/dn − Delete network printer connection." }, { "code": null, "e": 63533, "s": 63492, "text": "/dn − Delete network printer connection." }, { "code": null, "e": 63562, "s": 63533, "text": "/dd − Delete printer driver." }, { "code": null, "e": 63591, "s": 63562, "text": "/dd − Delete printer driver." }, { "code": null, "e": 63626, "s": 63591, "text": "/e − Display printing preferences." }, { "code": null, "e": 63661, "s": 63626, "text": "/e − Display printing preferences." }, { "code": null, "e": 63704, "s": 63661, "text": "/f[file] − Either inf file or output file." }, { "code": null, "e": 63747, "s": 63704, "text": "/f[file] − Either inf file or output file." }, { "code": null, "e": 63833, "s": 63747, "text": "/F[file] − Location of an INF file that the INF file specified with /f may depend on." }, { "code": null, "e": 63919, "s": 63833, "text": "/F[file] − Location of an INF file that the INF file specified with /f may depend on." }, { "code": null, "e": 63964, "s": 63919, "text": "/ia − Install printer driver using inf file." }, { "code": null, "e": 64009, "s": 63964, "text": "/ia − Install printer driver using inf file." }, { "code": null, "e": 64071, "s": 64009, "text": "/id − Install printer driver using add printer driver wizard." }, { "code": null, "e": 64133, "s": 64071, "text": "/id − Install printer driver using add printer driver wizard." }, { "code": null, "e": 64171, "s": 64133, "text": "/if − Install printer using inf file." }, { "code": null, "e": 64209, "s": 64171, "text": "/if − Install printer using inf file." }, { "code": null, "e": 64274, "s": 64209, "text": "/ii − Install printer using add printer wizard with an inf file." }, { "code": null, "e": 64339, "s": 64274, "text": "/ii − Install printer using add printer wizard with an inf file." }, { "code": null, "e": 64387, "s": 64339, "text": "/il − Install printer using add printer wizard." }, { "code": null, "e": 64435, "s": 64387, "text": "/il − Install printer using add printer wizard." }, { "code": null, "e": 64473, "s": 64435, "text": "/in − Add network printer connection." }, { "code": null, "e": 64511, "s": 64473, "text": "/in − Add network printer connection." }, { "code": null, "e": 64576, "s": 64511, "text": "/ip − Install printer using network printer installation wizard." }, { "code": null, "e": 64641, "s": 64576, "text": "/ip − Install printer using network printer installation wizard." }, { "code": null, "e": 64743, "s": 64641, "text": "/k − Print test page to specified printer, cannot be combined with command when installing a printer." }, { "code": null, "e": 64845, "s": 64743, "text": "/k − Print test page to specified printer, cannot be combined with command when installing a printer." }, { "code": null, "e": 64884, "s": 64845, "text": "/l[path] − Printer driver source path." }, { "code": null, "e": 64923, "s": 64884, "text": "/l[path] − Printer driver source path." }, { "code": null, "e": 64962, "s": 64923, "text": "/m[model] − Printer driver model name." }, { "code": null, "e": 65001, "s": 64962, "text": "/m[model] − Printer driver model name." }, { "code": null, "e": 65026, "s": 65001, "text": "/n[name] − Printer name." }, { "code": null, "e": 65051, "s": 65026, "text": "/n[name] − Printer name." }, { "code": null, "e": 65084, "s": 65051, "text": "/o − Display printer queue view." }, { "code": null, "e": 65117, "s": 65084, "text": "/o − Display printer queue view." }, { "code": null, "e": 65150, "s": 65117, "text": "/p − Display printer properties." }, { "code": null, "e": 65183, "s": 65150, "text": "/p − Display printer properties." }, { "code": null, "e": 65225, "s": 65183, "text": "/Ss − Store printer settings into a file." }, { "code": null, "e": 65267, "s": 65225, "text": "/Ss − Store printer settings into a file." }, { "code": null, "e": 65311, "s": 65267, "text": "/Sr − Restore printer settings from a file." }, { "code": null, "e": 65355, "s": 65311, "text": "/Sr − Restore printer settings from a file." }, { "code": null, "e": 65388, "s": 65355, "text": "/y − Set printer as the default." }, { "code": null, "e": 65421, "s": 65388, "text": "/y − Set printer as the default." }, { "code": null, "e": 65449, "s": 65421, "text": "/Xg − Get printer settings." }, { "code": null, "e": 65477, "s": 65449, "text": "/Xg − Get printer settings." }, { "code": null, "e": 65505, "s": 65477, "text": "/Xs − Set printer settings." }, { "code": null, "e": 65533, "s": 65505, "text": "/Xs − Set printer settings." }, { "code": null, "e": 65736, "s": 65533, "text": "There can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing." }, { "code": null, "e": 65881, "s": 65736, "text": "The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings." }, { "code": null, "e": 66127, "s": 65881, "text": "SET PrinterName = Test Printer\nSET file=%TEMP%\\Prt.txt\nRUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n \"%PrinterName%\" /f \"%file%\" /q\n\nIF EXIST \"%file%\" (\n ECHO %PrinterName% printer exists\n) ELSE (\n ECHO %PrinterName% printer does NOT exists\n)" }, { "code": null, "e": 66169, "s": 66127, "text": "The above command will do the following −" }, { "code": null, "e": 66269, "s": 66169, "text": "It will first set the printer name and set a file name which will hold the settings of the printer." }, { "code": null, "e": 66369, "s": 66269, "text": "It will first set the printer name and set a file name which will hold the settings of the printer." }, { "code": null, "e": 66530, "s": 66369, "text": "The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt" }, { "code": null, "e": 66691, "s": 66530, "text": "The RUNDLL32.EXE PRINTUI.DLL commands will be used to check if the printer actually exists by sending the configuration settings of the file to the file Prt.txt" }, { "code": null, "e": 66786, "s": 66691, "text": "Debugging a batch script becomes important when you are working on a big complex batch script." }, { "code": null, "e": 66848, "s": 66786, "text": "Following are the ways in which you can debug the batch file." }, { "code": null, "e": 67045, "s": 66848, "text": "A very simple debug option is to make use of echo command in your batch script wherever possible. It will display the message in the command prompt and help you debug where things have gone wrong." }, { "code": null, "e": 67369, "s": 67045, "text": "Here is a simple example that displays even numbers based on the input given. The echo command is used to display the result and also if the input is not given. Similarly, the echo command can be used in place when you think that the error can happen. For example, if the input given is a negative number, less than 2, etc." }, { "code": null, "e": 67531, "s": 67369, "text": "@echo off \nif [%1] == [] ( \n echo input value not provided \n goto stop \n) \nrem Display numbers \nfor /l %%n in (2,2,%1) do ( \n echo %%n \n) \n:stop \npause " }, { "code": null, "e": 67600, "s": 67531, "text": "C:\\>test.bat \n10 \n2 \n4 \n6 \n8 \n10 \n22\nPress any key to continue ... \n" }, { "code": null, "e": 67755, "s": 67600, "text": "Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing." }, { "code": null, "e": 67854, "s": 67755, "text": "In the example below, the batch script is paused as the input value is mandatory and not provided." }, { "code": null, "e": 67986, "s": 67854, "text": "@echo off \nif [%1] == [] ( \n echo input value not provided \n goto stop \n) else ( \n echo \"Valid value\" \n) \n:stop \npause " }, { "code": null, "e": 68057, "s": 67986, "text": "C:\\>test.bat \n input value not provided \nPress any key to continue.. \n" }, { "code": null, "e": 68277, "s": 68057, "text": "It might get hard to debug the error just looking at a bunch of echo displayed on the command prompt. Another easy way out is to log those messages in another file and view it step by step to understand what went wrong." }, { "code": null, "e": 68335, "s": 68277, "text": "Here is an example, consider the following test.bat file:" }, { "code": null, "e": 68360, "s": 68335, "text": "net statistics /Server \n" }, { "code": null, "e": 68449, "s": 68360, "text": "The command given in the .bat file is wrong. Let us log the message and see what we get." }, { "code": null, "e": 68501, "s": 68449, "text": "Execute the following command in your command line:" }, { "code": null, "e": 68547, "s": 68501, "text": "C:\\>test.bat > testlog.txt 2> testerrors.txt\n" }, { "code": null, "e": 68619, "s": 68547, "text": "The file testerrors.txt will display the error messages as shown below:" }, { "code": null, "e": 68778, "s": 68619, "text": "The option /SERVER is unknown. \nThe syntax of this command is: \nNET STATISTICS \n[WORKSTATION | SERVER] \nMore help is available by typing NET HELPMSG 3506.\n" }, { "code": null, "e": 68857, "s": 68778, "text": "Looking at the above file the developer can fix the program and execute again." }, { "code": null, "e": 68934, "s": 68857, "text": "Errorlevel returns 0 if the command executes successfully and 1 if it fails." }, { "code": null, "e": 68966, "s": 68934, "text": "Consider the following example:" }, { "code": null, "e": 69078, "s": 68966, "text": "@echo off \nPING google.com \nif errorlevel 1 GOTO stop \n:stop \n echo Unable to connect to google.com \npause\n" }, { "code": null, "e": 69132, "s": 69078, "text": "During execution, you can see errors as well as logs:" }, { "code": null, "e": 69160, "s": 69132, "text": "C:\\>test.bat > testlog.txt\n" }, { "code": null, "e": 69172, "s": 69160, "text": "testlog.txt" }, { "code": null, "e": 69710, "s": 69172, "text": "Pinging google.com [172.217.26.238] with 32 bytes of data: \nReply from 172.217.26.238: bytes=32 time=160ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=82ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=121ms TTL=111 \nReply from 172.217.26.238: bytes=32 time=108ms TTL=111 \nPing statistics for 172.217.26.238: \n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), \nApproximate round trip times in milli-seconds: \n Minimum = 82ms, Maximum = 160ms, Average = 117ms\n Connected successfully \nPress any key to continue . . .\n" }, { "code": null, "e": 69782, "s": 69710, "text": "In case of failure, you will see the following logs inside testlog.txt." }, { "code": null, "e": 69931, "s": 69782, "text": "Ping request could not find host google.com. Please check the name and try again. \nUnable to connect to google.com \nPress any key to continue . . .\n" }, { "code": null, "e": 70004, "s": 69931, "text": "Logging in is possible in Batch Script by using the redirection command." }, { "code": null, "e": 70046, "s": 70004, "text": "test.bat > testlog.txt 2> testerrors.txt\n" }, { "code": null, "e": 70121, "s": 70046, "text": "Create a file called test.bat and enter the following command in the file." }, { "code": null, "e": 70145, "s": 70121, "text": "net statistics /Server\n" }, { "code": null, "e": 70252, "s": 70145, "text": "The above command has an error because the option to the net statistics command is given in the wrong way." }, { "code": null, "e": 70306, "s": 70252, "text": "If the command with the above test.bat file is run as" }, { "code": null, "e": 70348, "s": 70306, "text": "test.bat > testlog.txt 2> testerrors.txt\n" }, { "code": null, "e": 70420, "s": 70348, "text": "And you open the file testerrors.txt, you will see the following error." }, { "code": null, "e": 70452, "s": 70420, "text": "The option /SERVER is unknown.\n" }, { "code": null, "e": 70484, "s": 70452, "text": "The syntax of this command is −" }, { "code": null, "e": 70523, "s": 70484, "text": "NET STATISTICS\n[WORKSTATION | SERVER]\n" }, { "code": null, "e": 70574, "s": 70523, "text": "More help is available by typing NET HELPMSG 3506." }, { "code": null, "e": 70670, "s": 70574, "text": "If you open the file called testlog.txt, it will show you a log of what commands were executed." }, { "code": null, "e": 70700, "s": 70670, "text": "C:\\tp>net statistics /Server\n" }, { "code": null, "e": 70707, "s": 70700, "text": " Print" }, { "code": null, "e": 70718, "s": 70707, "text": " Add Notes" } ]
Stock Price Prediction Based on Deep Learning | by Abhijit Roy | Towards Data Science
The stock market is known as a place where people can make a fortune if they can crack the mantra to successfully predict stock prices. Though it’s impossible to predict a stock price correctly most the time. So, the question arises, if humans can estimate and consider all factors to predict a movement or a future value of a stock, why can’t machines? Or, rephrasing, how can we make machines predict the value for a stock? Scientists, analysts, and researchers all over the world have been trying to devise a way to answer these questions for a long time now. In this article, I will try to demonstrate an approach towards so-called Algorithmic Trading. This is a complete research purpose-based approach. Please do not invest based on this algorithm. So, let’s start. A stock price may depend on several factors operating in the current world and stock market. We will try to take into account a combination of mainly two factors: The impact and correlation of stock prices of other companies i.e, how the increase and decrease of stock prices of the other companies affect the stock price of a given target companyThe past performances and records of the target company The impact and correlation of stock prices of other companies i.e, how the increase and decrease of stock prices of the other companies affect the stock price of a given target company The past performances and records of the target company I have seen several blogs that have mostly focussed on one of the factors, mostly 2nd factor. I think if we can manage to bring both these factors into effect, we can make our predictor a bit more robust. As a result, I have tried to achieve this using a combination of three deep learning models. Firstly, a neural network-based Regressor model which takes into account the impact of other companies on the target company. Secondly, a Recurrent Neural Network Model to study the past behavior of the target company and give results accordingly. For this purpose, I have used an LSTM layer. And, lastly, an Artificial Neural Networks which takes in both their predictions and helps reach a firm and robust conclusion. In this article, we will be using the S&P 500 companies database, though I have used the details of only 200 companies. I have collected the S&P list from the Wikipedia page using web scrapping. I am using this as a source because it is updated live I think. I have seen this method in some blogs, so I also used it. It seems to be a dependable source. import bs4 as bsimport pickleimport requestsdef save_tickers(): resp=requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup=bs.BeautifulSoup(resp.text) table=soup.find('table',{'class':'wikitable sortable'}) tickers=[] for row in table.findAll('tr')[1:]: ticker=row.findAll('td')[0].text[:-1] tickers.append(ticker)with open("tickers.pickle",'wb') as f: pickle.dump(tickers, f)return tickerssave_tickers() This code will help you to scrap the tickers of the top 500 companies. I have then collected their details from Yahoo using the Pandas web-data reader. import bs4 as bsimport pickleimport requestsimport datetime as dtimport osimport pandas as pdimport pandas_datareader.data as webdef fetch_data(): with open("tickers.pickle",'rb') as f: tickers=pickle.load(f)if not os.path.exists('stock_details'): os.makedirs('stock_details') count=200start= dt.datetime(2010,1,1) end=dt.datetime(2020,6,22) count=0 for ticker in tickers: if count==200: break count+=1 print(ticker) try: df=web.DataReader(ticker, 'yahoo', start, end) df.to_csv('stock_details/{}.csv'.format(ticker)) except: print("Error") continuefetch_data() This snippet of code will help to collect data from Yahoo using the web reader. I have kept a count of 200 because I wanted to use only 200 company details. In these 200 companies, we will have a target company and 199 companies that will help to reach a prediction about our target company. This code will generate a ‘stock_details’ folder which will have 200 company details from 1st January 2010 to 22nd June 2020. Each detail file will be saved by its stock’s ticker. I have chosen Amazon as my target stock. So, I will try to predict the stock prices for Amazon. Its ticker is AMZN. So, let’s see the structure of the detail files. This is the structure. It has ‘Date’ as the index feature. ‘High’ denotes the highest value of the day. ‘Low’ denotes the lowest. ‘Open’ is the opening Price and ‘Close’ is the closing for that Date. Now, sometimes close values are regulated by the companies. So the final value is the ‘Adj Close’ which is the same as ‘Close’ Value if the stock price is not regulated. ‘Volume’ is the amount of Stock of that company traded on that date. We will consider this ‘Adj Close’ value of each stock as the contributing feature of each stock on our target stock. So, we will rename the Adj Close of each stock as the corresponding stock ticker and include it in our feature set. import osimport pandas as pdimport pickledef compile(): with open("tickers.pickle",'rb') as f: tickers=pickle.load(f)main_df=pd.DataFrame()for count,ticker in enumerate(tickers): if 'AMZN' in ticker: continue if not os.path.exists('stock_details/{}.csv'.format(ticker)): continue df=pd.read_csv('stock_details/{}.csv'.format(ticker)) df.set_index('Date',inplace=True)df.rename(columns={'Adj Close': ticker}, inplace=True) df.drop(['Open','High','Low',"Close",'Volume'],axis=1,inplace=True)if main_df.empty: main_df=df else: main_df=main_df.join(df,how='outer')print(main_df.head()) main_df.to_csv('Dataset_temp.csv')compile() This snippet will help us to pick the Adjusted Close column of each stock other than our target stock which is AMZN, rename the column as the ticker and merge it in our feature set. It will produce a feature set like this. The Date is the index and corresponding to the Date, each ticker’s “Adj Close” value. Now, We will see there are a few empty columns initially. This is because these companies didn’t start to participate in the stock market back in 2010. This will give us a feature set of 200 columns containing 199 company’s values and the Date. Now, let’s focus on our target stock the AMZN stock. If we start visualizing each of our given column values for the target stock we obtain these. Now, let’s visualize, our stock using the candlestick notation. I am using Pandas version 0.24.2 for this. There may be an issue as in the current versions this module is depreciated. import datetime as dtimport matplotlib.pyplot as pltfrom matplotlib import stylefrom mpl_finance import candlestick_ohlcimport matplotlib.dates as mdatesimport pandas as pddf=pd.read_csv('stock_details/AMZN.csv',index_col=0,parse_dates=True)df_ohlc= df['Adj Close'].resample('10D').ohlc()df_volume=df['Volume'].resample('10D').sum()df_ohlc.reset_index(inplace=True)df_ohlc['Date']=df_ohlc['Date'].map(mdates.date2num)ax1=plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)ax2=plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1 , sharex=ax1)ax1.xaxis_date()candlestick_ohlc(ax1,df_ohlc.values, width=2, colorup='g')ax2.fill_between(df_volume.index.map(mdates.date2num),df_volume.values,0)plt.show() This code will give us the candlestick notation. Now, let’s devise some features that will help us to predict our target. We will calculate the 50 moving average. This characteristic is used by a lot of traders for predictions. df['Moving_av']= df['Adj Close'].rolling(window=50,min_periods=0).mean() This snippet will help us produce the moving average. Actually, it is the mean of the i-50 to i values of the “Adj Close” values for the ith index. Now, we will try to obtain two more features, Rate of increase in volume and rate of increase in Adjusted Close for our stock i=1rate_increase_in_vol=[0]rate_increase_in_adj_close=[0]while i<len(df): rate_increase_in_vol.append(df.iloc[i]['Volume']-df.iloc[i-1]['Volume']) rate_increase_in_adj_close.append(df.iloc[i]['Adj Close']-df.iloc[i-1]['Adj Close']) i+=1 df['Increase_in_vol']=rate_increase_in_voldf['Increase_in_adj_close']=rate_increase_in_adj_close This snippet will help us obtain these features. Now, our feature file for our target stock is ready. Now, we merge both these feature files to make the main feature set. Index(['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close', 'Moving_av', 'Increase_in_vol', 'Increase_in_adj_close', 'MMM', ... 'FITB', 'FE', 'FRC', 'FISV', 'FLT', 'FLIR', 'FLS', 'FMC', 'F', 'Date'], dtype='object', length=207) These are the columns of our main feature set. It has 207 columns 200 from the other companies list and 7 from our target stock feature set anchored on the date column. So, we have 207 columns. In this part, we will study the impact of the other stocks on our target stock. We will try to predict the High, Low, Open, and Close of our Amazon stock. At first, let’s analyze our data. Here, we can see we have found some correlations. So, from our plots, it is evident that we will have some correlations in our dataset. So, next, we drop the Open, Close, High, Low values from our training dataset and use them as the target labels or values set. We also drop the Volume and Date because they won’t have a correlation. from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) We split our sets into training and testing. from tensorflow.keras.callbacks import ModelCheckpointfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activation, Flattenfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_error from sklearn.metrics import accuracy_scoredef model(): mod=Sequential() mod.add(Dense(32, kernel_initializer='normal',input_dim = 200, activation='relu')) mod.add(Dense(64, kernel_initializer='normal',activation='relu')) mod.add(Dense(128, kernel_initializer='normal',activation='relu')) mod.add(Dense(256, kernel_initializer='normal',activation='relu')) mod.add(Dense(4, kernel_initializer='normal',activation='linear')) mod.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy','mean_absolute_error']) mod.summary() return mod This is our model that will be used for regression. It can be run using this snippet: from tensorflow.keras.wrappers.scikit_learn import KerasRegressorregressor = KerasRegressor(build_fn=model, batch_size=16,epochs=2000)import tensorflow as tfcallback=tf.keras.callbacks.ModelCheckpoint(filepath='Regressor_model.h5', monitor='mean_absolute_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto')results=regressor.fit(X_train,y_train,callbacks=[callback]) I have used Keras Regressor for this purpose. Saved best weights and used 2000 epochs. Mean Absolute Error is our Loss function. We have an input of 200 after dropping the columns. We are going to obtain four values for each input, High, Low, Open, Close. y_pred= regressor.predict(X_test)import numpy as npy_pred_mod=[]y_test_mod=[]for i in range(0,4): j=0 y_pred_temp=[] y_test_temp=[] while(j<len(y_test)): y_pred_temp.append(y_pred[j][i]) y_test_temp.append(y_test[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp)) y_test_mod.append(np.array(y_test_temp)) This gives us the predicted values for our test set. This snippet helps to obtain them in a parsed format. Now, we can see our model has performed quite well considering most of the points lie on the regression line and there are very few outliers. Here we complete our regression part. Next, we will move to the RNN part. We will be using RNN for the past analysis of our target stock. So we will be working with the Target Stock Feature file only. Now, here we will use LSTM layers that work on RNN principles but work on a gated approach. The LSTM helps the RNN to keep the memory over a long period of time, solving the vanishing and exploding gradient problems. We are not going to talk about it in detail here. You can find the details here. This is our dataset for LSTM. Now, we need to predict High, Low, Open, Close. So, now, we will drop the “Date” as it has no correlation. High Low Open Close Volume Adj Close \0 137.279999 134.520004 137.089996 134.520004 4523000 134.520004 1 136.610001 133.139999 136.250000 133.899994 7599900 133.899994 2 135.479996 131.809998 133.429993 134.690002 8851900 134.690002 3 134.729996 131.649994 134.600006 132.250000 7178800 132.250000 4 132.320007 128.800003 132.009995 130.000000 11030200 130.000000 Moving_av Increase_in_vol Increase_in_adj_close 0 134.520004 0.0 0.000000 1 134.209999 3076900.0 -0.620010 2 134.370000 1252000.0 0.790009 3 133.840000 -1673100.0 -2.440002 Now, our input will be this Dataframe’s values. So our input will have 9 columns and correspondingly our output will have 4 columns, High, Low, Open, Close of our target stock. We need to create the train and test set for the LSTM model. For this purpose, we will split our data of length 2636 records into two parts. We will be using 0–2200 records as the train set and 2200–2636 as our test set. We select the target set comprising of the 4 target columns from our train set. df_train=df_main[:2200]df_target=df_train[['High','Low','Open','Close']] Now, we scale our data to make our model converge easily, as we have large variations of values in our data set. sc = MinMaxScaler(feature_range = (0, 1))target_set=df_target.valuestrain_set=df_train.valuestraining_set_scaled = sc.fit_transform(train_set)target_set_scaled = sc.fit_transform(target_set) Thus, we have obtained the scaled data for our LSTM model. LSTM model takes in series data and produces output. Our LSTM is many to many RNN model. So, we need to produce a series of data for this purpose. To do this, we have started from the 50th index and move to the length of the training set. We have appended 0–49, which is 50 values to a list. We have created such lists for all our features. So, our Input has (n x 50 x 9) dimensional data for our training set. We have 9 features and each feature is a list of the feature values for an extended period of 50 days. n is the number of such series obtained from the given dataset. Now, our target set is the value of the target columns on the 51st day. We obtain this using, X_train = []y_train = []for i in range(50,len(train_set)): X_train.append(training_set_scaled[i-50:i,:]) y_train.append(target_set_scaled[i,:]) X_train, y_train = np.array(X_train), np.array(y_train) Now, let’s observe the shapes of the train and target sets. print(X_train.shape)(2150, 50, 9)print(y_train.shape)(2150, 4) Let’s design our models. from sklearn.metrics import accuracy_scorefrom tensorflow.keras.layers import BatchNormalizationimport datetime as dtfrom sklearn import model_selectionfrom sklearn.metrics import confusion_matrixfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pdfrom sklearn.preprocessing import MinMaxScalerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densefrom tensorflow.keras.layers import LSTMfrom tensorflow.keras.layers import Dropoutdef model(): mod=Sequential() mod.add(LSTM(units = 64, return_sequences = True, input_shape = (X_train.shape[1], 9))) mod.add(Dropout(0.2)) mod.add(BatchNormalization()) mod.add(LSTM(units = 64, return_sequences = True)) mod.add(Dropout(0.1)) mod.add(BatchNormalization()) mod.add((LSTM(units = 64))) mod.add(Dropout(0.1)) mod.add(BatchNormalization()) mod.add((Dense(units = 16, activation='tanh'))) mod.add(BatchNormalization()) mod.add((Dense(units = 4, activation='tanh'))) mod.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy','mean_squared_error']) mod.summary() return mod This is our LSTM model. I have used Keras layers here. The loss function is the Mean Squared Error. We have used Adam Optimizer. To train our model we will be using this snippet. import tensorflow as tfcallback=tf.keras.callbacks.ModelCheckpoint(filepath='./RNN_model.h5', monitor='mean_squared_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', save_freq='epoch')RNN_model.fit(X_train, y_train, epochs = 2000, batch_size = 32,callbacks=[callback]) Our model is now trained. Let us focus on the testing part. We have 2200 to 2636 records for our test values. So we obtain our target values by picking the four columns Open, Close, High, Low of our stock. df_test=df_main[2200:]df_target_test=df_test[['High','Low','Open','Close']]target_set_test=df_target_test.valuestest_set=df_test.values To test also, we need to transform our test feature dataset and form a series of 50 feature values for this set as we did in case of the train set. predicted_stock_price = RNN_model.predict(X_test)predicted_stock_price = sc.inverse_transform(predicted_stock_price)print(predicted_stock_price) This code snippet helps to obtain the predicted results as we desired. array([[1690.364 , 1610.5382, 1643.4277, 1643.8912], [1687.384 , 1607.5323, 1640.3225, 1640.7366], [1688.7346, 1608.965 , 1641.6777, 1642.0984], ..., [2567.6138, 2510.703 , 2522.8406, 2538.787 ], [2576.5056, 2519.5195, 2531.803 , 2547.9304], [2578.5886, 2521.65 , 2533.9177, 2550.0896]], dtype=float32) The results are so obtained. Now, if we plot them accordingly with the actual values of our target columns, we will obtain the following plot. There are 4 lines if we observe, this is due to the fact that we have 4 columns as the target. We can see the model has quite obtained the curve patterns, in most of the places. Now, if we plot them individually, we will obtain 4 plots as follows. Thus, we conclude the study of the individual target stock based on its past values of the stock using LSTM. Now, we move to the Covering ANN or concluding portion. Now, this is the concluding portion. We have obtained two different results studying two different areas that may affect the stock of a company using two exclusive models. Now, we will try to merge both the results. We will do this by merging the obtained results and training our Artificial Neural Network over the whole thing. We had 4 target columns for the above two discussed models. For the final conclusion, we will try to predict only two columns, the High and the Low Column of our target stock. So, for this, we predict our full dataset using both the models. The Regressor model produces 2636 predicted values. The snippet and results are as follows: saved_model_regressor=tf.keras.models.load_model('Regressor_model.h5')Regressor_prediction=saved_model_regressor(X)import numpy as npy_pred_mod=[]for i in range(0,4): j=0 y_pred_temp=[] while(j<len(Regressor_prediction)): y_pred_temp.append(Regressor_prediction[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp))Y_pred=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_pred_mod[2],y_pred_mod[3])),columns=['High_regress','Low_regress','Open_regress','Close_regress']) This is the snippet. It creates a Dataframe of length 2636 with four predicted value columns. Y_pred.head() We save it as a CSV for further use. Now, similarly, we do this for the LSTM network. We obtain one value for the first 50 values as the first 50 values are our first test set. So, the division is 0–49 obtains 1st value, 1–50 obtains the 2nd value, and so on. We obtain a total of 2586 values from the RNN. Snippet: saved_model_RNN=tf.keras.models.load_model('RNN_model.h5')RNN_prediction=saved_model_RNN.predict(X_test)import numpy as npy_pred_mod=[]for i in range(0,4): j=0 y_pred_temp=[] while(j<len(RNN_prediction)): y_pred_temp.append(RNN_prediction[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp))Y_pred=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_pred_mod[2],y_pred_mod[3])),columns=['High_RNN','Low_RNN','Open_RNN','Close_RNN']) This snippet generates a Dataframe with the RNN prediction of the target values. Our predictions of both models are ready. We need to drop the 0–50 index from the Regression predictions because there are no RNN predictions for those values. We are now ready to merge the results. So, after merging the results we obtain a Dataframe of 2586 values with 8 columns. df=pd.concat([df1,df2],axis=1)df.head() This is the concatenated result. The whole thing will become the feature set for our ANN model. So, what about our target set. Our target set will comprise of the original High and Low values of our Target stock of Amazon from the original dataset. df1=pd.read_csv("dataset_target_2.csv")target_high=[]target_low=[]i=50while i<len(df1): target_high.append(df1.iloc[i]['High']) target_low.append(df1.iloc[i]['Low']) i+=1df['Target_high']=target_highdf['Target_low']=target_lowdf.to_csv('feature.csv',index=False) This snippet helps to merge all the columns in our feature set. There are 10 columns. 8 feature columns from the two models and the High and Low values of the target stock as the target values. Our new feature set looks like this. This is our feature histogram plots. Here also, we get a pretty good correlation from the plots. Now let’s design and train our Artificial Neural Network model. X_Df=df_main[['High_regress','Low_regress','Open_regress','Close_regress','High_RNN','Low_RNN','Open_RNN','Close_RNN']].valuesy_Df=df_main[['Target_high','Target_low']].valuesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X_Df, y_Df, test_size=0.3) Now, let’s see our model design. from tensorflow.keras.callbacks import ModelCheckpointfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activation, Flattenfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_error from sklearn.metrics import accuracy_scoredef model(): mod=Sequential() mod.add(Dense(32, kernel_initializer='normal',input_dim = 8, activation='relu')) mod.add(Dense(64, kernel_initializer='normal',activation='relu')) mod.add(Dense(128, kernel_initializer='normal',activation='relu')) mod.add(Dense(2, kernel_initializer='normal',activation='linear')) mod.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy','mean_absolute_error']) mod.summary() return mod This our ANN model. As we see, the input dimension of our model is 8. This is because we have input 8 feature columns 4 columns obtained from each model’s output. The output layer has 2 nodes for High and Low columns for the target stock. I have used the loss function as Mean Absolute Error, Optimizer as Adam’s optimizer. We can run the model using the following snippet: import tensorflow as tfmodel_ANN=model()callback=tf.keras.callbacks.ModelCheckpoint(filepath='ANN_model.h5', monitor='mean_absolute_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto')results=model_ANN.fit(X_train,y_train, epochs = 2000, batch_size = 32,callbacks=[callback]) After we train the model, we will be using the predicted model to predict our test set and check for the performance. y_pred=model_ANN.predict(X_test)import numpy as npy_pred_mod=[]y_test_mod=[]for i in range(0,2): j=0 y_pred_temp=[] y_test_temp=[] while(j<len(y_test)): y_pred_temp.append(y_pred[j][i]) y_test_temp.append(y_test[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp)) y_test_mod.append(np.array(y_test_temp))df_res=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_test_mod[0],y_test_mod[1])),columns=['Pred_high','Pred_low','Actual_high','Actual_low']) Our predictor predicts two values for each featured record. So, this code snippet helps to obtain the predicted values of the two columns and the test values and represent them as a Dataframe. Now, let’s plot and check. import matplotlib.pyplot as pltax1=plt.subplot2grid((4,1), (0,0), rowspan=5, colspan=1)ax1.plot(df_res_2.index, df_res_2['Pred_high'], label="Pred_high")ax1.plot(df_res_2.index, df_res_2['Actual_high'], label="Actual_high")plt.legend(loc="upper left")plt.xticks(rotation=90)plt.show() This snippet helps to see the predicted and actual variations. If we want to check our model performances. We can do this by using this snippet: fig, ax = plt.subplots()ax.scatter(y_test_mod[0], y_pred_mod[0])ax.plot([y_test_mod[0].min(),y_test_mod[0].max()], [y_test_mod[0].min(), y_test_mod[0].max()], 'k--', lw=4)ax.set_xlabel('Measured')ax.set_ylabel('Predicted')plt.show() This will obtain: These linear plots show that there is a linear relationship between our models predicted values and the actual values. So, our composite model did quite well on the predictions of High and Low column values of our target Amazon Stock. So, here we conclude our entire purpose. In this article, we have seen how we can build an algorithmic trading model based on composite Neural Nets. I hope this article will help. The whole Github code is: here. Please find the further task on this subject: here.
[ { "code": null, "e": 735, "s": 172, "text": "The stock market is known as a place where people can make a fortune if they can crack the mantra to successfully predict stock prices. Though it’s impossible to predict a stock price correctly most the time. So, the question arises, if humans can estimate and consider all factors to predict a movement or a future value of a stock, why can’t machines? Or, rephrasing, how can we make machines predict the value for a stock? Scientists, analysts, and researchers all over the world have been trying to devise a way to answer these questions for a long time now." }, { "code": null, "e": 944, "s": 735, "text": "In this article, I will try to demonstrate an approach towards so-called Algorithmic Trading. This is a complete research purpose-based approach. Please do not invest based on this algorithm. So, let’s start." }, { "code": null, "e": 1107, "s": 944, "text": "A stock price may depend on several factors operating in the current world and stock market. We will try to take into account a combination of mainly two factors:" }, { "code": null, "e": 1347, "s": 1107, "text": "The impact and correlation of stock prices of other companies i.e, how the increase and decrease of stock prices of the other companies affect the stock price of a given target companyThe past performances and records of the target company" }, { "code": null, "e": 1532, "s": 1347, "text": "The impact and correlation of stock prices of other companies i.e, how the increase and decrease of stock prices of the other companies affect the stock price of a given target company" }, { "code": null, "e": 1588, "s": 1532, "text": "The past performances and records of the target company" }, { "code": null, "e": 1793, "s": 1588, "text": "I have seen several blogs that have mostly focussed on one of the factors, mostly 2nd factor. I think if we can manage to bring both these factors into effect, we can make our predictor a bit more robust." }, { "code": null, "e": 2306, "s": 1793, "text": "As a result, I have tried to achieve this using a combination of three deep learning models. Firstly, a neural network-based Regressor model which takes into account the impact of other companies on the target company. Secondly, a Recurrent Neural Network Model to study the past behavior of the target company and give results accordingly. For this purpose, I have used an LSTM layer. And, lastly, an Artificial Neural Networks which takes in both their predictions and helps reach a firm and robust conclusion." }, { "code": null, "e": 2659, "s": 2306, "text": "In this article, we will be using the S&P 500 companies database, though I have used the details of only 200 companies. I have collected the S&P list from the Wikipedia page using web scrapping. I am using this as a source because it is updated live I think. I have seen this method in some blogs, so I also used it. It seems to be a dependable source." }, { "code": null, "e": 3092, "s": 2659, "text": "import bs4 as bsimport pickleimport requestsdef save_tickers(): resp=requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup=bs.BeautifulSoup(resp.text) table=soup.find('table',{'class':'wikitable sortable'}) tickers=[] for row in table.findAll('tr')[1:]: ticker=row.findAll('td')[0].text[:-1] tickers.append(ticker)with open(\"tickers.pickle\",'wb') as f: pickle.dump(tickers, f)return tickerssave_tickers()" }, { "code": null, "e": 3163, "s": 3092, "text": "This code will help you to scrap the tickers of the top 500 companies." }, { "code": null, "e": 3244, "s": 3163, "text": "I have then collected their details from Yahoo using the Pandas web-data reader." }, { "code": null, "e": 3830, "s": 3244, "text": "import bs4 as bsimport pickleimport requestsimport datetime as dtimport osimport pandas as pdimport pandas_datareader.data as webdef fetch_data(): with open(\"tickers.pickle\",'rb') as f: tickers=pickle.load(f)if not os.path.exists('stock_details'): os.makedirs('stock_details') count=200start= dt.datetime(2010,1,1) end=dt.datetime(2020,6,22) count=0 for ticker in tickers: if count==200: break count+=1 print(ticker) try: df=web.DataReader(ticker, 'yahoo', start, end) df.to_csv('stock_details/{}.csv'.format(ticker)) except: print(\"Error\") continuefetch_data()" }, { "code": null, "e": 4122, "s": 3830, "text": "This snippet of code will help to collect data from Yahoo using the web reader. I have kept a count of 200 because I wanted to use only 200 company details. In these 200 companies, we will have a target company and 199 companies that will help to reach a prediction about our target company." }, { "code": null, "e": 4248, "s": 4122, "text": "This code will generate a ‘stock_details’ folder which will have 200 company details from 1st January 2010 to 22nd June 2020." }, { "code": null, "e": 4418, "s": 4248, "text": "Each detail file will be saved by its stock’s ticker. I have chosen Amazon as my target stock. So, I will try to predict the stock prices for Amazon. Its ticker is AMZN." }, { "code": null, "e": 4467, "s": 4418, "text": "So, let’s see the structure of the detail files." }, { "code": null, "e": 4906, "s": 4467, "text": "This is the structure. It has ‘Date’ as the index feature. ‘High’ denotes the highest value of the day. ‘Low’ denotes the lowest. ‘Open’ is the opening Price and ‘Close’ is the closing for that Date. Now, sometimes close values are regulated by the companies. So the final value is the ‘Adj Close’ which is the same as ‘Close’ Value if the stock price is not regulated. ‘Volume’ is the amount of Stock of that company traded on that date." }, { "code": null, "e": 5139, "s": 4906, "text": "We will consider this ‘Adj Close’ value of each stock as the contributing feature of each stock on our target stock. So, we will rename the Adj Close of each stock as the corresponding stock ticker and include it in our feature set." }, { "code": null, "e": 5781, "s": 5139, "text": "import osimport pandas as pdimport pickledef compile(): with open(\"tickers.pickle\",'rb') as f: tickers=pickle.load(f)main_df=pd.DataFrame()for count,ticker in enumerate(tickers): if 'AMZN' in ticker: continue if not os.path.exists('stock_details/{}.csv'.format(ticker)): continue df=pd.read_csv('stock_details/{}.csv'.format(ticker)) df.set_index('Date',inplace=True)df.rename(columns={'Adj Close': ticker}, inplace=True) df.drop(['Open','High','Low',\"Close\",'Volume'],axis=1,inplace=True)if main_df.empty: main_df=df else: main_df=main_df.join(df,how='outer')print(main_df.head()) main_df.to_csv('Dataset_temp.csv')compile()" }, { "code": null, "e": 5963, "s": 5781, "text": "This snippet will help us to pick the Adjusted Close column of each stock other than our target stock which is AMZN, rename the column as the ticker and merge it in our feature set." }, { "code": null, "e": 6335, "s": 5963, "text": "It will produce a feature set like this. The Date is the index and corresponding to the Date, each ticker’s “Adj Close” value. Now, We will see there are a few empty columns initially. This is because these companies didn’t start to participate in the stock market back in 2010. This will give us a feature set of 200 columns containing 199 company’s values and the Date." }, { "code": null, "e": 6482, "s": 6335, "text": "Now, let’s focus on our target stock the AMZN stock. If we start visualizing each of our given column values for the target stock we obtain these." }, { "code": null, "e": 6666, "s": 6482, "text": "Now, let’s visualize, our stock using the candlestick notation. I am using Pandas version 0.24.2 for this. There may be an issue as in the current versions this module is depreciated." }, { "code": null, "e": 7366, "s": 6666, "text": "import datetime as dtimport matplotlib.pyplot as pltfrom matplotlib import stylefrom mpl_finance import candlestick_ohlcimport matplotlib.dates as mdatesimport pandas as pddf=pd.read_csv('stock_details/AMZN.csv',index_col=0,parse_dates=True)df_ohlc= df['Adj Close'].resample('10D').ohlc()df_volume=df['Volume'].resample('10D').sum()df_ohlc.reset_index(inplace=True)df_ohlc['Date']=df_ohlc['Date'].map(mdates.date2num)ax1=plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)ax2=plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1 , sharex=ax1)ax1.xaxis_date()candlestick_ohlc(ax1,df_ohlc.values, width=2, colorup='g')ax2.fill_between(df_volume.index.map(mdates.date2num),df_volume.values,0)plt.show()" }, { "code": null, "e": 7415, "s": 7366, "text": "This code will give us the candlestick notation." }, { "code": null, "e": 7488, "s": 7415, "text": "Now, let’s devise some features that will help us to predict our target." }, { "code": null, "e": 7594, "s": 7488, "text": "We will calculate the 50 moving average. This characteristic is used by a lot of traders for predictions." }, { "code": null, "e": 7667, "s": 7594, "text": "df['Moving_av']= df['Adj Close'].rolling(window=50,min_periods=0).mean()" }, { "code": null, "e": 7815, "s": 7667, "text": "This snippet will help us produce the moving average. Actually, it is the mean of the i-50 to i values of the “Adj Close” values for the ith index." }, { "code": null, "e": 7941, "s": 7815, "text": "Now, we will try to obtain two more features, Rate of increase in volume and rate of increase in Adjusted Close for our stock" }, { "code": null, "e": 8287, "s": 7941, "text": "i=1rate_increase_in_vol=[0]rate_increase_in_adj_close=[0]while i<len(df): rate_increase_in_vol.append(df.iloc[i]['Volume']-df.iloc[i-1]['Volume']) rate_increase_in_adj_close.append(df.iloc[i]['Adj Close']-df.iloc[i-1]['Adj Close']) i+=1 df['Increase_in_vol']=rate_increase_in_voldf['Increase_in_adj_close']=rate_increase_in_adj_close" }, { "code": null, "e": 8336, "s": 8287, "text": "This snippet will help us obtain these features." }, { "code": null, "e": 8389, "s": 8336, "text": "Now, our feature file for our target stock is ready." }, { "code": null, "e": 8458, "s": 8389, "text": "Now, we merge both these feature files to make the main feature set." }, { "code": null, "e": 8711, "s": 8458, "text": "Index(['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close', 'Moving_av', 'Increase_in_vol', 'Increase_in_adj_close', 'MMM', ... 'FITB', 'FE', 'FRC', 'FISV', 'FLT', 'FLIR', 'FLS', 'FMC', 'F', 'Date'], dtype='object', length=207)" }, { "code": null, "e": 8758, "s": 8711, "text": "These are the columns of our main feature set." }, { "code": null, "e": 8905, "s": 8758, "text": "It has 207 columns 200 from the other companies list and 7 from our target stock feature set anchored on the date column. So, we have 207 columns." }, { "code": null, "e": 9060, "s": 8905, "text": "In this part, we will study the impact of the other stocks on our target stock. We will try to predict the High, Low, Open, and Close of our Amazon stock." }, { "code": null, "e": 9094, "s": 9060, "text": "At first, let’s analyze our data." }, { "code": null, "e": 9144, "s": 9094, "text": "Here, we can see we have found some correlations." }, { "code": null, "e": 9429, "s": 9144, "text": "So, from our plots, it is evident that we will have some correlations in our dataset. So, next, we drop the Open, Close, High, Low values from our training dataset and use them as the target labels or values set. We also drop the Volume and Date because they won’t have a correlation." }, { "code": null, "e": 9554, "s": 9429, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)" }, { "code": null, "e": 9599, "s": 9554, "text": "We split our sets into training and testing." }, { "code": null, "e": 10495, "s": 9599, "text": "from tensorflow.keras.callbacks import ModelCheckpointfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activation, Flattenfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_error from sklearn.metrics import accuracy_scoredef model(): mod=Sequential() mod.add(Dense(32, kernel_initializer='normal',input_dim = 200, activation='relu')) mod.add(Dense(64, kernel_initializer='normal',activation='relu')) mod.add(Dense(128, kernel_initializer='normal',activation='relu')) mod.add(Dense(256, kernel_initializer='normal',activation='relu')) mod.add(Dense(4, kernel_initializer='normal',activation='linear')) mod.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy','mean_absolute_error']) mod.summary() return mod" }, { "code": null, "e": 10547, "s": 10495, "text": "This is our model that will be used for regression." }, { "code": null, "e": 10581, "s": 10547, "text": "It can be run using this snippet:" }, { "code": null, "e": 11183, "s": 10581, "text": "from tensorflow.keras.wrappers.scikit_learn import KerasRegressorregressor = KerasRegressor(build_fn=model, batch_size=16,epochs=2000)import tensorflow as tfcallback=tf.keras.callbacks.ModelCheckpoint(filepath='Regressor_model.h5', monitor='mean_absolute_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto')results=regressor.fit(X_train,y_train,callbacks=[callback])" }, { "code": null, "e": 11439, "s": 11183, "text": "I have used Keras Regressor for this purpose. Saved best weights and used 2000 epochs. Mean Absolute Error is our Loss function. We have an input of 200 after dropping the columns. We are going to obtain four values for each input, High, Low, Open, Close." }, { "code": null, "e": 11801, "s": 11439, "text": "y_pred= regressor.predict(X_test)import numpy as npy_pred_mod=[]y_test_mod=[]for i in range(0,4): j=0 y_pred_temp=[] y_test_temp=[] while(j<len(y_test)): y_pred_temp.append(y_pred[j][i]) y_test_temp.append(y_test[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp)) y_test_mod.append(np.array(y_test_temp))" }, { "code": null, "e": 11908, "s": 11801, "text": "This gives us the predicted values for our test set. This snippet helps to obtain them in a parsed format." }, { "code": null, "e": 12050, "s": 11908, "text": "Now, we can see our model has performed quite well considering most of the points lie on the regression line and there are very few outliers." }, { "code": null, "e": 12124, "s": 12050, "text": "Here we complete our regression part. Next, we will move to the RNN part." }, { "code": null, "e": 12343, "s": 12124, "text": "We will be using RNN for the past analysis of our target stock. So we will be working with the Target Stock Feature file only. Now, here we will use LSTM layers that work on RNN principles but work on a gated approach." }, { "code": null, "e": 12549, "s": 12343, "text": "The LSTM helps the RNN to keep the memory over a long period of time, solving the vanishing and exploding gradient problems. We are not going to talk about it in detail here. You can find the details here." }, { "code": null, "e": 12579, "s": 12549, "text": "This is our dataset for LSTM." }, { "code": null, "e": 12686, "s": 12579, "text": "Now, we need to predict High, Low, Open, Close. So, now, we will drop the “Date” as it has no correlation." }, { "code": null, "e": 13395, "s": 12686, "text": "High Low Open Close Volume Adj Close \\0 137.279999 134.520004 137.089996 134.520004 4523000 134.520004 1 136.610001 133.139999 136.250000 133.899994 7599900 133.899994 2 135.479996 131.809998 133.429993 134.690002 8851900 134.690002 3 134.729996 131.649994 134.600006 132.250000 7178800 132.250000 4 132.320007 128.800003 132.009995 130.000000 11030200 130.000000 Moving_av Increase_in_vol Increase_in_adj_close 0 134.520004 0.0 0.000000 1 134.209999 3076900.0 -0.620010 2 134.370000 1252000.0 0.790009 3 133.840000 -1673100.0 -2.440002" }, { "code": null, "e": 13572, "s": 13395, "text": "Now, our input will be this Dataframe’s values. So our input will have 9 columns and correspondingly our output will have 4 columns, High, Low, Open, Close of our target stock." }, { "code": null, "e": 13633, "s": 13572, "text": "We need to create the train and test set for the LSTM model." }, { "code": null, "e": 13873, "s": 13633, "text": "For this purpose, we will split our data of length 2636 records into two parts. We will be using 0–2200 records as the train set and 2200–2636 as our test set. We select the target set comprising of the 4 target columns from our train set." }, { "code": null, "e": 13946, "s": 13873, "text": "df_train=df_main[:2200]df_target=df_train[['High','Low','Open','Close']]" }, { "code": null, "e": 14059, "s": 13946, "text": "Now, we scale our data to make our model converge easily, as we have large variations of values in our data set." }, { "code": null, "e": 14250, "s": 14059, "text": "sc = MinMaxScaler(feature_range = (0, 1))target_set=df_target.valuestrain_set=df_train.valuestraining_set_scaled = sc.fit_transform(train_set)target_set_scaled = sc.fit_transform(target_set)" }, { "code": null, "e": 14309, "s": 14250, "text": "Thus, we have obtained the scaled data for our LSTM model." }, { "code": null, "e": 14650, "s": 14309, "text": "LSTM model takes in series data and produces output. Our LSTM is many to many RNN model. So, we need to produce a series of data for this purpose. To do this, we have started from the 50th index and move to the length of the training set. We have appended 0–49, which is 50 values to a list. We have created such lists for all our features." }, { "code": null, "e": 14959, "s": 14650, "text": "So, our Input has (n x 50 x 9) dimensional data for our training set. We have 9 features and each feature is a list of the feature values for an extended period of 50 days. n is the number of such series obtained from the given dataset. Now, our target set is the value of the target columns on the 51st day." }, { "code": null, "e": 14981, "s": 14959, "text": "We obtain this using," }, { "code": null, "e": 15190, "s": 14981, "text": "X_train = []y_train = []for i in range(50,len(train_set)): X_train.append(training_set_scaled[i-50:i,:]) y_train.append(target_set_scaled[i,:]) X_train, y_train = np.array(X_train), np.array(y_train)" }, { "code": null, "e": 15250, "s": 15190, "text": "Now, let’s observe the shapes of the train and target sets." }, { "code": null, "e": 15313, "s": 15250, "text": "print(X_train.shape)(2150, 50, 9)print(y_train.shape)(2150, 4)" }, { "code": null, "e": 15338, "s": 15313, "text": "Let’s design our models." }, { "code": null, "e": 16545, "s": 15338, "text": "from sklearn.metrics import accuracy_scorefrom tensorflow.keras.layers import BatchNormalizationimport datetime as dtfrom sklearn import model_selectionfrom sklearn.metrics import confusion_matrixfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitimport numpy as npimport pandas as pdfrom sklearn.preprocessing import MinMaxScalerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densefrom tensorflow.keras.layers import LSTMfrom tensorflow.keras.layers import Dropoutdef model(): mod=Sequential() mod.add(LSTM(units = 64, return_sequences = True, input_shape = (X_train.shape[1], 9))) mod.add(Dropout(0.2)) mod.add(BatchNormalization()) mod.add(LSTM(units = 64, return_sequences = True)) mod.add(Dropout(0.1)) mod.add(BatchNormalization()) mod.add((LSTM(units = 64))) mod.add(Dropout(0.1)) mod.add(BatchNormalization()) mod.add((Dense(units = 16, activation='tanh'))) mod.add(BatchNormalization()) mod.add((Dense(units = 4, activation='tanh'))) mod.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy','mean_squared_error']) mod.summary() return mod" }, { "code": null, "e": 16674, "s": 16545, "text": "This is our LSTM model. I have used Keras layers here. The loss function is the Mean Squared Error. We have used Adam Optimizer." }, { "code": null, "e": 16724, "s": 16674, "text": "To train our model we will be using this snippet." }, { "code": null, "e": 17273, "s": 16724, "text": "import tensorflow as tfcallback=tf.keras.callbacks.ModelCheckpoint(filepath='./RNN_model.h5', monitor='mean_squared_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', save_freq='epoch')RNN_model.fit(X_train, y_train, epochs = 2000, batch_size = 32,callbacks=[callback])" }, { "code": null, "e": 17299, "s": 17273, "text": "Our model is now trained." }, { "code": null, "e": 17333, "s": 17299, "text": "Let us focus on the testing part." }, { "code": null, "e": 17479, "s": 17333, "text": "We have 2200 to 2636 records for our test values. So we obtain our target values by picking the four columns Open, Close, High, Low of our stock." }, { "code": null, "e": 17615, "s": 17479, "text": "df_test=df_main[2200:]df_target_test=df_test[['High','Low','Open','Close']]target_set_test=df_target_test.valuestest_set=df_test.values" }, { "code": null, "e": 17763, "s": 17615, "text": "To test also, we need to transform our test feature dataset and form a series of 50 feature values for this set as we did in case of the train set." }, { "code": null, "e": 17908, "s": 17763, "text": "predicted_stock_price = RNN_model.predict(X_test)predicted_stock_price = sc.inverse_transform(predicted_stock_price)print(predicted_stock_price)" }, { "code": null, "e": 17979, "s": 17908, "text": "This code snippet helps to obtain the predicted results as we desired." }, { "code": null, "e": 18319, "s": 17979, "text": "array([[1690.364 , 1610.5382, 1643.4277, 1643.8912], [1687.384 , 1607.5323, 1640.3225, 1640.7366], [1688.7346, 1608.965 , 1641.6777, 1642.0984], ..., [2567.6138, 2510.703 , 2522.8406, 2538.787 ], [2576.5056, 2519.5195, 2531.803 , 2547.9304], [2578.5886, 2521.65 , 2533.9177, 2550.0896]], dtype=float32)" }, { "code": null, "e": 18348, "s": 18319, "text": "The results are so obtained." }, { "code": null, "e": 18462, "s": 18348, "text": "Now, if we plot them accordingly with the actual values of our target columns, we will obtain the following plot." }, { "code": null, "e": 18640, "s": 18462, "text": "There are 4 lines if we observe, this is due to the fact that we have 4 columns as the target. We can see the model has quite obtained the curve patterns, in most of the places." }, { "code": null, "e": 18710, "s": 18640, "text": "Now, if we plot them individually, we will obtain 4 plots as follows." }, { "code": null, "e": 18875, "s": 18710, "text": "Thus, we conclude the study of the individual target stock based on its past values of the stock using LSTM. Now, we move to the Covering ANN or concluding portion." }, { "code": null, "e": 19204, "s": 18875, "text": "Now, this is the concluding portion. We have obtained two different results studying two different areas that may affect the stock of a company using two exclusive models. Now, we will try to merge both the results. We will do this by merging the obtained results and training our Artificial Neural Network over the whole thing." }, { "code": null, "e": 19380, "s": 19204, "text": "We had 4 target columns for the above two discussed models. For the final conclusion, we will try to predict only two columns, the High and the Low Column of our target stock." }, { "code": null, "e": 19497, "s": 19380, "text": "So, for this, we predict our full dataset using both the models. The Regressor model produces 2636 predicted values." }, { "code": null, "e": 19537, "s": 19497, "text": "The snippet and results are as follows:" }, { "code": null, "e": 20062, "s": 19537, "text": "saved_model_regressor=tf.keras.models.load_model('Regressor_model.h5')Regressor_prediction=saved_model_regressor(X)import numpy as npy_pred_mod=[]for i in range(0,4): j=0 y_pred_temp=[] while(j<len(Regressor_prediction)): y_pred_temp.append(Regressor_prediction[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp))Y_pred=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_pred_mod[2],y_pred_mod[3])),columns=['High_regress','Low_regress','Open_regress','Close_regress'])" }, { "code": null, "e": 20156, "s": 20062, "text": "This is the snippet. It creates a Dataframe of length 2636 with four predicted value columns." }, { "code": null, "e": 20170, "s": 20156, "text": "Y_pred.head()" }, { "code": null, "e": 20207, "s": 20170, "text": "We save it as a CSV for further use." }, { "code": null, "e": 20477, "s": 20207, "text": "Now, similarly, we do this for the LSTM network. We obtain one value for the first 50 values as the first 50 values are our first test set. So, the division is 0–49 obtains 1st value, 1–50 obtains the 2nd value, and so on. We obtain a total of 2586 values from the RNN." }, { "code": null, "e": 20486, "s": 20477, "text": "Snippet:" }, { "code": null, "e": 20972, "s": 20486, "text": "saved_model_RNN=tf.keras.models.load_model('RNN_model.h5')RNN_prediction=saved_model_RNN.predict(X_test)import numpy as npy_pred_mod=[]for i in range(0,4): j=0 y_pred_temp=[] while(j<len(RNN_prediction)): y_pred_temp.append(RNN_prediction[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp))Y_pred=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_pred_mod[2],y_pred_mod[3])),columns=['High_RNN','Low_RNN','Open_RNN','Close_RNN'])" }, { "code": null, "e": 21053, "s": 20972, "text": "This snippet generates a Dataframe with the RNN prediction of the target values." }, { "code": null, "e": 21252, "s": 21053, "text": "Our predictions of both models are ready. We need to drop the 0–50 index from the Regression predictions because there are no RNN predictions for those values. We are now ready to merge the results." }, { "code": null, "e": 21335, "s": 21252, "text": "So, after merging the results we obtain a Dataframe of 2586 values with 8 columns." }, { "code": null, "e": 21375, "s": 21335, "text": "df=pd.concat([df1,df2],axis=1)df.head()" }, { "code": null, "e": 21408, "s": 21375, "text": "This is the concatenated result." }, { "code": null, "e": 21624, "s": 21408, "text": "The whole thing will become the feature set for our ANN model. So, what about our target set. Our target set will comprise of the original High and Low values of our Target stock of Amazon from the original dataset." }, { "code": null, "e": 21896, "s": 21624, "text": "df1=pd.read_csv(\"dataset_target_2.csv\")target_high=[]target_low=[]i=50while i<len(df1): target_high.append(df1.iloc[i]['High']) target_low.append(df1.iloc[i]['Low']) i+=1df['Target_high']=target_highdf['Target_low']=target_lowdf.to_csv('feature.csv',index=False)" }, { "code": null, "e": 22090, "s": 21896, "text": "This snippet helps to merge all the columns in our feature set. There are 10 columns. 8 feature columns from the two models and the High and Low values of the target stock as the target values." }, { "code": null, "e": 22127, "s": 22090, "text": "Our new feature set looks like this." }, { "code": null, "e": 22288, "s": 22127, "text": "This is our feature histogram plots. Here also, we get a pretty good correlation from the plots. Now let’s design and train our Artificial Neural Network model." }, { "code": null, "e": 22594, "s": 22288, "text": "X_Df=df_main[['High_regress','Low_regress','Open_regress','Close_regress','High_RNN','Low_RNN','Open_RNN','Close_RNN']].valuesy_Df=df_main[['Target_high','Target_low']].valuesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X_Df, y_Df, test_size=0.3)" }, { "code": null, "e": 22627, "s": 22594, "text": "Now, let’s see our model design." }, { "code": null, "e": 23451, "s": 22627, "text": "from tensorflow.keras.callbacks import ModelCheckpointfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activation, Flattenfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import mean_absolute_error from sklearn.metrics import accuracy_scoredef model(): mod=Sequential() mod.add(Dense(32, kernel_initializer='normal',input_dim = 8, activation='relu')) mod.add(Dense(64, kernel_initializer='normal',activation='relu')) mod.add(Dense(128, kernel_initializer='normal',activation='relu')) mod.add(Dense(2, kernel_initializer='normal',activation='linear')) mod.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy','mean_absolute_error']) mod.summary() return mod" }, { "code": null, "e": 23690, "s": 23451, "text": "This our ANN model. As we see, the input dimension of our model is 8. This is because we have input 8 feature columns 4 columns obtained from each model’s output. The output layer has 2 nodes for High and Low columns for the target stock." }, { "code": null, "e": 23775, "s": 23690, "text": "I have used the loss function as Mean Absolute Error, Optimizer as Adam’s optimizer." }, { "code": null, "e": 23825, "s": 23775, "text": "We can run the model using the following snippet:" }, { "code": null, "e": 24336, "s": 23825, "text": "import tensorflow as tfmodel_ANN=model()callback=tf.keras.callbacks.ModelCheckpoint(filepath='ANN_model.h5', monitor='mean_absolute_error', verbose=0, save_best_only=True, save_weights_only=False, mode='auto')results=model_ANN.fit(X_train,y_train, epochs = 2000, batch_size = 32,callbacks=[callback])" }, { "code": null, "e": 24454, "s": 24336, "text": "After we train the model, we will be using the predicted model to predict our test set and check for the performance." }, { "code": null, "e": 24962, "s": 24454, "text": "y_pred=model_ANN.predict(X_test)import numpy as npy_pred_mod=[]y_test_mod=[]for i in range(0,2): j=0 y_pred_temp=[] y_test_temp=[] while(j<len(y_test)): y_pred_temp.append(y_pred[j][i]) y_test_temp.append(y_test[j][i]) j+=1 y_pred_mod.append(np.array(y_pred_temp)) y_test_mod.append(np.array(y_test_temp))df_res=pd.DataFrame(list(zip(y_pred_mod[0],y_pred_mod[1],y_test_mod[0],y_test_mod[1])),columns=['Pred_high','Pred_low','Actual_high','Actual_low'])" }, { "code": null, "e": 25155, "s": 24962, "text": "Our predictor predicts two values for each featured record. So, this code snippet helps to obtain the predicted values of the two columns and the test values and represent them as a Dataframe." }, { "code": null, "e": 25182, "s": 25155, "text": "Now, let’s plot and check." }, { "code": null, "e": 25467, "s": 25182, "text": "import matplotlib.pyplot as pltax1=plt.subplot2grid((4,1), (0,0), rowspan=5, colspan=1)ax1.plot(df_res_2.index, df_res_2['Pred_high'], label=\"Pred_high\")ax1.plot(df_res_2.index, df_res_2['Actual_high'], label=\"Actual_high\")plt.legend(loc=\"upper left\")plt.xticks(rotation=90)plt.show()" }, { "code": null, "e": 25530, "s": 25467, "text": "This snippet helps to see the predicted and actual variations." }, { "code": null, "e": 25612, "s": 25530, "text": "If we want to check our model performances. We can do this by using this snippet:" }, { "code": null, "e": 25845, "s": 25612, "text": "fig, ax = plt.subplots()ax.scatter(y_test_mod[0], y_pred_mod[0])ax.plot([y_test_mod[0].min(),y_test_mod[0].max()], [y_test_mod[0].min(), y_test_mod[0].max()], 'k--', lw=4)ax.set_xlabel('Measured')ax.set_ylabel('Predicted')plt.show()" }, { "code": null, "e": 25863, "s": 25845, "text": "This will obtain:" }, { "code": null, "e": 25982, "s": 25863, "text": "These linear plots show that there is a linear relationship between our models predicted values and the actual values." }, { "code": null, "e": 26139, "s": 25982, "text": "So, our composite model did quite well on the predictions of High and Low column values of our target Amazon Stock. So, here we conclude our entire purpose." }, { "code": null, "e": 26278, "s": 26139, "text": "In this article, we have seen how we can build an algorithmic trading model based on composite Neural Nets. I hope this article will help." }, { "code": null, "e": 26310, "s": 26278, "text": "The whole Github code is: here." } ]
Count of substrings of a binary string containing K ones in C++
We are given a string of binary numbers i.e. combination of 0’s and 1’s and an integer value k and the task is to calculate the count of substrings formed with the given binary string having given k 1’s. Input − string str = ‘10000100000’, k = 2 Output − Count of substrings of a binary string containing K ones are − 6 Explanation − Substrings that can be formed from the given string are 1, 10, 100, 1000, 10000, 010, 100001, 10001, 1001, 101, 11, 1000010. So there are 6 substrings having k number of 1’s i.e. exactly 2 ones. Input − string str = ‘10000100000’, k = 3 Output − Count of substrings of a binary string containing K ones are − 0 Explanation − We are given with an integer value of k as 3 and if we check our string containing binary numbers, it has only 2 ones. So there is no possibility of substring having given k number of ones. Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k. Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k. Calculate the length of the string using length() function and pass the data to the function for further processing. Calculate the length of the string using length() function and pass the data to the function for further processing. Declare a temporary variable count and total as 0 for storing the substrings with k ones. Declare a temporary variable count and total as 0 for storing the substrings with k ones. Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1. Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1. Start loop FOR from 0 till the length of an array Start loop FOR from 0 till the length of an array Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k]. Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k]. Return count Return count Print the result. Print the result. Live Demo #include <bits/stdc++.h> using namespace std; int sub_k_ones(string str, int length, int k){ int count = 0; int total_1 = 0; int arr_fre[length + 1] = {0}; arr_fre[0] = 1; for (int i = 0; i < length; i++){ total_1 = total_1 + (str[i] - '0'); if (total_1 >= k){ count = count + arr_fre[total_1 - k]; } arr_fre[total_1]++; } return count; } int main(){ string str = "10000100000"; int length = str.length(); int k = 2; cout<<"Count of substrings of a binary string containing K ones are: "<<sub_k_ones(str, length, k) << endl; return 0; } If we run the above code it will generate the following output − Count of substrings of a binary string containing K ones are: 6
[ { "code": null, "e": 1266, "s": 1062, "text": "We are given a string of binary numbers i.e. combination of 0’s and 1’s and an integer value k and the task is to calculate the count of substrings formed with the given binary string having given k 1’s." }, { "code": null, "e": 1308, "s": 1266, "text": "Input − string str = ‘10000100000’, k = 2" }, { "code": null, "e": 1382, "s": 1308, "text": "Output − Count of substrings of a binary string containing K ones are − 6" }, { "code": null, "e": 1591, "s": 1382, "text": "Explanation − Substrings that can be formed from the given string are 1, 10, 100, 1000, 10000, 010, 100001, 10001, 1001, 101, 11, 1000010. So there are 6 substrings having k number of 1’s i.e. exactly 2 ones." }, { "code": null, "e": 1633, "s": 1591, "text": "Input − string str = ‘10000100000’, k = 3" }, { "code": null, "e": 1707, "s": 1633, "text": "Output − Count of substrings of a binary string containing K ones are − 0" }, { "code": null, "e": 1911, "s": 1707, "text": "Explanation − We are given with an integer value of k as 3 and if we check our string containing binary numbers, it has only 2 ones. So there is no possibility of substring having given k number of ones." }, { "code": null, "e": 2006, "s": 1911, "text": "Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k." }, { "code": null, "e": 2101, "s": 2006, "text": "Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k." }, { "code": null, "e": 2218, "s": 2101, "text": "Calculate the length of the string using length() function and pass the data to the function for further processing." }, { "code": null, "e": 2335, "s": 2218, "text": "Calculate the length of the string using length() function and pass the data to the function for further processing." }, { "code": null, "e": 2425, "s": 2335, "text": "Declare a temporary variable count and total as 0 for storing the substrings with k ones." }, { "code": null, "e": 2515, "s": 2425, "text": "Declare a temporary variable count and total as 0 for storing the substrings with k ones." }, { "code": null, "e": 2666, "s": 2515, "text": "Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1." }, { "code": null, "e": 2817, "s": 2666, "text": "Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1." }, { "code": null, "e": 2867, "s": 2817, "text": "Start loop FOR from 0 till the length of an array" }, { "code": null, "e": 2917, "s": 2867, "text": "Start loop FOR from 0 till the length of an array" }, { "code": null, "e": 3029, "s": 2917, "text": "Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k]." }, { "code": null, "e": 3141, "s": 3029, "text": "Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k]." }, { "code": null, "e": 3154, "s": 3141, "text": "Return count" }, { "code": null, "e": 3167, "s": 3154, "text": "Return count" }, { "code": null, "e": 3185, "s": 3167, "text": "Print the result." }, { "code": null, "e": 3203, "s": 3185, "text": "Print the result." }, { "code": null, "e": 3214, "s": 3203, "text": " Live Demo" }, { "code": null, "e": 3820, "s": 3214, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint sub_k_ones(string str, int length, int k){\n int count = 0;\n int total_1 = 0;\n int arr_fre[length + 1] = {0};\n arr_fre[0] = 1;\n for (int i = 0; i < length; i++){\n total_1 = total_1 + (str[i] - '0');\n if (total_1 >= k){\n count = count + arr_fre[total_1 - k];\n }\n arr_fre[total_1]++;\n }\n return count;\n}\nint main(){\n string str = \"10000100000\";\n int length = str.length();\n int k = 2;\n cout<<\"Count of substrings of a binary string containing K ones are: \"<<sub_k_ones(str, length, k) << endl;\n return 0;\n}" }, { "code": null, "e": 3885, "s": 3820, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3949, "s": 3885, "text": "Count of substrings of a binary string containing K ones are: 6" } ]
Hadoop - Streaming
Hadoop streaming is a utility that comes with the Hadoop distribution. This utility allows you to create and run Map/Reduce jobs with any executable or script as the mapper and/or the reducer. For Hadoop streaming, we are considering the word-count problem. Any job in Hadoop must have two phases: mapper and reducer. We have written codes for the mapper and the reducer in python script to run it under Hadoop. One can also write the same in Perl and Ruby. !/usr/bin/python import sys # Input takes from standard input for myline in sys.stdin: # Remove whitespace either side myline = myline.strip() # Break the line into words words = myline.split() # Iterate the words list for myword in words: # Write the results to standard output print '%s\t%s' % (myword, 1) Make sure this file has execution permission (chmod +x /home/ expert/hadoop-1.2.1/mapper.py). #!/usr/bin/python from operator import itemgetter import sys current_word = "" current_count = 0 word = "" # Input takes from standard input for myline in sys.stdin: # Remove whitespace either side myline = myline.strip() # Split the input we got from mapper.py word, count = myline.split('\t', 1) # Convert count variable to integer try: count = int(count) except ValueError: # Count was not a number, so silently ignore this line continue if current_word == word: current_count += count else: if current_word: # Write result to standard output print '%s\t%s' % (current_word, current_count) current_count = count current_word = word # Do not forget to output the last word if needed! if current_word == word: print '%s\t%s' % (current_word, current_count) Save the mapper and reducer codes in mapper.py and reducer.py in Hadoop home directory. Make sure these files have execution permission (chmod +x mapper.py and chmod +x reducer.py). As python is indentation sensitive so the same code can be download from the below link. $ $HADOOP_HOME/bin/hadoop jar contrib/streaming/hadoop-streaming-1. 2.1.jar \ -input input_dirs \ -output output_dir \ -mapper <path/mapper.py \ -reducer <path/reducer.py Where "\" is used for line continuation for clear readability. ./bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -input myinput -output myoutput -mapper /home/expert/hadoop-1.2.1/mapper.py -reducer /home/expert/hadoop-1.2.1/reducer.py In the above example, both the mapper and the reducer are python scripts that read the input from standard input and emit the output to standard output. The utility will create a Map/Reduce job, submit the job to an appropriate cluster, and monitor the progress of the job until it completes. When a script is specified for mappers, each mapper task will launch the script as a separate process when the mapper is initialized. As the mapper task runs, it converts its inputs into lines and feed the lines to the standard input (STDIN) of the process. In the meantime, the mapper collects the line-oriented outputs from the standard output (STDOUT) of the process and converts each line into a key/value pair, which is collected as the output of the mapper. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) will be the value. If there is no tab character in the line, then the entire line is considered as the key and the value is null. However, this can be customized, as per one need. When a script is specified for reducers, each reducer task will launch the script as a separate process, then the reducer is initialized. As the reducer task runs, it converts its input key/values pairs into lines and feeds the lines to the standard input (STDIN) of the process. In the meantime, the reducer collects the line-oriented outputs from the standard output (STDOUT) of the process, converts each line into a key/value pair, which is collected as the output of the reducer. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) is the value. However, this can be customized as per specific requirements. 39 Lectures 2.5 hours Arnab Chakraborty 65 Lectures 6 hours Arnab Chakraborty 12 Lectures 1 hours Pranjal Srivastava 24 Lectures 6.5 hours Pari Margu 89 Lectures 11.5 hours TELCOMA Global 43 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2044, "s": 1851, "text": "Hadoop streaming is a utility that comes with the Hadoop distribution. This utility allows you to create and run Map/Reduce jobs with any executable or script as the mapper and/or the reducer." }, { "code": null, "e": 2309, "s": 2044, "text": "For Hadoop streaming, we are considering the word-count problem. Any job in Hadoop must have two phases: mapper and reducer. We have written codes for the mapper and the reducer in python script to run it under Hadoop. One can also write the same in Perl and Ruby." }, { "code": null, "e": 2658, "s": 2309, "text": "!/usr/bin/python\n\nimport sys\n\n# Input takes from standard input for myline in sys.stdin: \n # Remove whitespace either side \n myline = myline.strip() \n\n # Break the line into words \n words = myline.split() \n\n # Iterate the words list\n for myword in words:\n # Write the results to standard output \n print '%s\\t%s' % (myword, 1)\n" }, { "code": null, "e": 2752, "s": 2658, "text": "Make sure this file has execution permission (chmod +x /home/ expert/hadoop-1.2.1/mapper.py)." }, { "code": null, "e": 3615, "s": 2752, "text": "#!/usr/bin/python\n\nfrom operator import itemgetter \nimport sys \n\ncurrent_word = \"\"\ncurrent_count = 0 \nword = \"\" \n\n# Input takes from standard input for myline in sys.stdin: \n # Remove whitespace either side \n myline = myline.strip() \n\n # Split the input we got from mapper.py word, \n count = myline.split('\\t', 1) \n\n # Convert count variable to integer \n try: \n count = int(count) \n\n except ValueError: \n # Count was not a number, so silently ignore this line continue\n\n if current_word == word: \n current_count += count \n else: \n if current_word: \n # Write result to standard output print '%s\\t%s' % (current_word, current_count) \n \n current_count = count\n current_word = word\n\n# Do not forget to output the last word if needed! \nif current_word == word: \n print '%s\\t%s' % (current_word, current_count)\n" }, { "code": null, "e": 3886, "s": 3615, "text": "Save the mapper and reducer codes in mapper.py and reducer.py in Hadoop home directory. Make sure these files have execution permission (chmod +x mapper.py and chmod +x reducer.py). As python is indentation sensitive so the same code can be download from the below link." }, { "code": null, "e": 4073, "s": 3886, "text": "$ $HADOOP_HOME/bin/hadoop jar contrib/streaming/hadoop-streaming-1.\n2.1.jar \\\n -input input_dirs \\ \n -output output_dir \\ \n -mapper <path/mapper.py \\ \n -reducer <path/reducer.py\n" }, { "code": null, "e": 4136, "s": 4073, "text": "Where \"\\\" is used for line continuation for clear readability." }, { "code": null, "e": 4321, "s": 4136, "text": "./bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -input myinput -output myoutput -mapper /home/expert/hadoop-1.2.1/mapper.py -reducer /home/expert/hadoop-1.2.1/reducer.py\n" }, { "code": null, "e": 4614, "s": 4321, "text": "In the above example, both the mapper and the reducer are python scripts that read the input from standard input and emit the output to standard output. The utility will create a Map/Reduce job, submit the job to an appropriate cluster, and monitor the progress of the job until it completes." }, { "code": null, "e": 5387, "s": 4614, "text": "When a script is specified for mappers, each mapper task will launch the script as a separate process when the mapper is initialized. As the mapper task runs, it converts its inputs into lines and feed the lines to the standard input (STDIN) of the process. In the meantime, the mapper collects the line-oriented outputs from the standard output (STDOUT) of the process and converts each line into a key/value pair, which is collected as the output of the mapper. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) will be the value. If there is no tab character in the line, then the entire line is considered as the key and the value is null. However, this can be customized, as per one need." }, { "code": null, "e": 6077, "s": 5387, "text": "When a script is specified for reducers, each reducer task will launch the script as a separate process, then the reducer is initialized. As the reducer task runs, it converts its input key/values pairs into lines and feeds the lines to the standard input (STDIN) of the process. In the meantime, the reducer collects the line-oriented outputs from the standard output (STDOUT) of the process, converts each line into a key/value pair, which is collected as the output of the reducer. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) is the value. However, this can be customized as per specific requirements." }, { "code": null, "e": 6112, "s": 6077, "text": "\n 39 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6131, "s": 6112, "text": " Arnab Chakraborty" }, { "code": null, "e": 6164, "s": 6131, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6183, "s": 6164, "text": " Arnab Chakraborty" }, { "code": null, "e": 6216, "s": 6183, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 6236, "s": 6216, "text": " Pranjal Srivastava" }, { "code": null, "e": 6271, "s": 6236, "text": "\n 24 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6283, "s": 6271, "text": " Pari Margu" }, { "code": null, "e": 6319, "s": 6283, "text": "\n 89 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6335, "s": 6319, "text": " TELCOMA Global" }, { "code": null, "e": 6370, "s": 6335, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6388, "s": 6370, "text": " Bigdata Engineer" }, { "code": null, "e": 6395, "s": 6388, "text": " Print" }, { "code": null, "e": 6406, "s": 6395, "text": " Add Notes" } ]
How to remove all the elements from a set in javascript?
The Set class in JavaScript provides a clear method to remove all elements from a given set object. This method can be used as follows − let mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(1); mySet.add(3); mySet.add("a"); console.log(mySet) mySet.clear(); console.log(mySet) Set { 1, 2, 3, 'a' } Set { } You can also individually remove the elements by iterating over them. let mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(1); mySet.add(3); mySet.add("a"); console.log(mySet) for(let i of mySet) { console.log(i) mySet.delete(i) } console.log(mySet) Set { 1, 2, 3, 'a' } Set { }
[ { "code": null, "e": 1199, "s": 1062, "text": "The Set class in JavaScript provides a clear method to remove all elements from a given set object. This method can be used as follows −" }, { "code": null, "e": 1347, "s": 1199, "text": "let mySet = new Set();\nmySet.add(1);\nmySet.add(2);\nmySet.add(1);\nmySet.add(3);\nmySet.add(\"a\");\nconsole.log(mySet)\nmySet.clear();\nconsole.log(mySet)" }, { "code": null, "e": 1376, "s": 1347, "text": "Set { 1, 2, 3, 'a' }\nSet { }" }, { "code": null, "e": 1446, "s": 1376, "text": "You can also individually remove the elements by iterating over them." }, { "code": null, "e": 1640, "s": 1446, "text": "let mySet = new Set();\nmySet.add(1);\nmySet.add(2);\nmySet.add(1);\nmySet.add(3);\nmySet.add(\"a\");\nconsole.log(mySet)\nfor(let i of mySet) {\n console.log(i)\n mySet.delete(i)\n}\nconsole.log(mySet)" }, { "code": null, "e": 1669, "s": 1640, "text": "Set { 1, 2, 3, 'a' }\nSet { }" } ]
How to handle Null values while working with JDBC?
SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use: Avoid using getXXX( ) methods that return primitive data types. Avoid using getXXX( ) methods that return primitive data types. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL. Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL. Following code snippet demonstrates how to handle null values in Java. Statement stmt = conn.createStatement( ); String sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); int id = rs.getInt(1); if( rs.wasNull( ) ) { id = 0; }
[ { "code": null, "e": 1210, "s": 1062, "text": "SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use:" }, { "code": null, "e": 1274, "s": 1210, "text": "Avoid using getXXX( ) methods that return primitive data types." }, { "code": null, "e": 1338, "s": 1274, "text": "Avoid using getXXX( ) methods that return primitive data types." }, { "code": null, "e": 1556, "s": 1338, "text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null." }, { "code": null, "e": 1774, "s": 1556, "text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null." }, { "code": null, "e": 2017, "s": 1774, "text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL." }, { "code": null, "e": 2260, "s": 2017, "text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL." }, { "code": null, "e": 2331, "s": 2260, "text": "Following code snippet demonstrates how to handle null values in Java." }, { "code": null, "e": 2526, "s": 2331, "text": "Statement stmt = conn.createStatement( );\nString sql = \"SELECT id, first, last, age FROM Employees\";\nResultSet rs = stmt.executeQuery(sql);\nint id = rs.getInt(1);\nif( rs.wasNull( ) ) {\nid = 0;\n}" } ]
Matplotlib.dates.epoch2num() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.dates.epoch2num() function is used to convert an epoch or a sequence of epochs to a new date format from the day since 0001. Syntax: matplotlib.dates.epoch2num(e) Parameters: e: It can be an epoch or a sequence of epochs. Returns: A new date format since day 0001. Example 1: import randomimport matplotlib.pyplot as pltimport matplotlib.dates as mdates # generate some random data# for approx 5 yrsrandom_data = [float(random.randint(1487517521, 14213254713)) for _ in range(1000)] # convert the epoch format to# matplotlib date format mpl_data = mdates.epoch2num(random_data) # plotting the graphfig, axes = plt.subplots(1, 1)axes.hist(mpl_data, bins = 51, color ='green')locator = mdates.AutoDateLocator() axes.xaxis.set_major_locator(locator)axes.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) plt.show() Output: Example 2: from tkinter import *from tkinter import ttkimport time import matplotlibimport queuefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tkfrom matplotlib.figure import Figureimport matplotlib.animation as animationimport matplotlib.dates as mdate root = Tk() graphXData = queue.Queue()graphYData = queue.Queue() def animate(objData): line.set_data(list(graphXData.queue), list(graphYData.queue)) axes.relim() axes.autoscale_view() figure = Figure(figsize =(5, 5), dpi = 100)axes = figure.add_subplot(111)axes.xaxis_date() line, = axes.plot([], [])axes.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M')) canvas = FigureCanvasTkAgg(figure, root)canvas.get_tk_widget().pack(side = BOTTOM, fill = BOTH, expand = True) for cnt in range (600): graphXData.put(matplotlib.dates.epoch2num(time.time()-(600-cnt))) graphYData.put(0) ani = animation.FuncAnimation(figure, animate, interval = 1000) root.mainloop() Output: Python-matplotlib Python Write From Home 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 Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24330, "s": 24302, "text": "\n19 Apr, 2020" }, { "code": null, "e": 24542, "s": 24330, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 24682, "s": 24542, "text": "The matplotlib.dates.epoch2num() function is used to convert an epoch or a sequence of epochs to a new date format from the day since 0001." }, { "code": null, "e": 24720, "s": 24682, "text": "Syntax: matplotlib.dates.epoch2num(e)" }, { "code": null, "e": 24732, "s": 24720, "text": "Parameters:" }, { "code": null, "e": 24779, "s": 24732, "text": "e: It can be an epoch or a sequence of epochs." }, { "code": null, "e": 24822, "s": 24779, "text": "Returns: A new date format since day 0001." }, { "code": null, "e": 24833, "s": 24822, "text": "Example 1:" }, { "code": "import randomimport matplotlib.pyplot as pltimport matplotlib.dates as mdates # generate some random data# for approx 5 yrsrandom_data = [float(random.randint(1487517521, 14213254713)) for _ in range(1000)] # convert the epoch format to# matplotlib date format mpl_data = mdates.epoch2num(random_data) # plotting the graphfig, axes = plt.subplots(1, 1)axes.hist(mpl_data, bins = 51, color ='green')locator = mdates.AutoDateLocator() axes.xaxis.set_major_locator(locator)axes.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) plt.show()", "e": 25434, "s": 24833, "text": null }, { "code": null, "e": 25442, "s": 25434, "text": "Output:" }, { "code": null, "e": 25453, "s": 25442, "text": "Example 2:" }, { "code": "from tkinter import *from tkinter import ttkimport time import matplotlibimport queuefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tkfrom matplotlib.figure import Figureimport matplotlib.animation as animationimport matplotlib.dates as mdate root = Tk() graphXData = queue.Queue()graphYData = queue.Queue() def animate(objData): line.set_data(list(graphXData.queue), list(graphYData.queue)) axes.relim() axes.autoscale_view() figure = Figure(figsize =(5, 5), dpi = 100)axes = figure.add_subplot(111)axes.xaxis_date() line, = axes.plot([], [])axes.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M')) canvas = FigureCanvasTkAgg(figure, root)canvas.get_tk_widget().pack(side = BOTTOM, fill = BOTH, expand = True) for cnt in range (600): graphXData.put(matplotlib.dates.epoch2num(time.time()-(600-cnt))) graphYData.put(0) ani = animation.FuncAnimation(figure, animate, interval = 1000) root.mainloop()", "e": 26510, "s": 25453, "text": null }, { "code": null, "e": 26518, "s": 26510, "text": "Output:" }, { "code": null, "e": 26536, "s": 26518, "text": "Python-matplotlib" }, { "code": null, "e": 26543, "s": 26536, "text": "Python" }, { "code": null, "e": 26559, "s": 26543, "text": "Write From Home" }, { "code": null, "e": 26657, "s": 26559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26666, "s": 26657, "text": "Comments" }, { "code": null, "e": 26679, "s": 26666, "text": "Old Comments" }, { "code": null, "e": 26697, "s": 26679, "text": "Python Dictionary" }, { "code": null, "e": 26729, "s": 26697, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26751, "s": 26729, "text": "Enumerate() in Python" }, { "code": null, "e": 26786, "s": 26751, "text": "Read a file line by line in Python" }, { "code": null, "e": 26816, "s": 26786, "text": "Iterate over a list in Python" }, { "code": null, "e": 26852, "s": 26816, "text": "Convert integer to string in Python" }, { "code": null, "e": 26888, "s": 26852, "text": "Convert string to integer in Python" }, { "code": null, "e": 26949, "s": 26888, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26965, "s": 26949, "text": "Python infinity" } ]
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks
28 Jun, 2021 Let m[0]...m[4] be mutexes (binary semaphores) and P[0] .... P[4] be processes.Suppose each process P[i] executes the following: wait (m[i]); wait(m[(i+1) mode 4]); ------ release (m[i]); release (m[(i+1)mod 4]); This could cause:(A) Thrashing(B) Deadlock(C) Starvation, but not deadlock(D) None of the aboveAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-1/Quiz of this Question GATE-CS-2000 GATE-GATE-CS-2000 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE CS 1997 | Question 25 GATE | GATE CS 2019 | Question 37 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24386, "s": 24358, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24515, "s": 24386, "text": "Let m[0]...m[4] be mutexes (binary semaphores) and P[0] .... P[4] be processes.Suppose each process P[i] executes the following:" }, { "code": null, "e": 24608, "s": 24515, "text": " wait (m[i]); wait(m[(i+1) mode 4]);\n\n ------\n\n release (m[i]); release (m[(i+1)mod 4]); " }, { "code": null, "e": 24821, "s": 24608, "text": "This could cause:(A) Thrashing(B) Deadlock(C) Starvation, but not deadlock(D) None of the aboveAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-1/Quiz of this Question" }, { "code": null, "e": 24834, "s": 24821, "text": "GATE-CS-2000" }, { "code": null, "e": 24852, "s": 24834, "text": "GATE-GATE-CS-2000" }, { "code": null, "e": 24857, "s": 24852, "text": "GATE" }, { "code": null, "e": 24955, "s": 24857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24964, "s": 24955, "text": "Comments" }, { "code": null, "e": 24977, "s": 24964, "text": "Old Comments" }, { "code": null, "e": 25011, "s": 24977, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25053, "s": 25011, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25087, "s": 25053, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25129, "s": 25087, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25171, "s": 25129, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25213, "s": 25171, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25247, "s": 25213, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 25281, "s": 25247, "text": "GATE | GATE CS 1997 | Question 25" }, { "code": null, "e": 25315, "s": 25281, "text": "GATE | GATE CS 2019 | Question 37" } ]
Python - Find the number of prime numbers within a given range of numbers
When it is required to find the prime numbers within a given range of numbers, the range is entered and it is iterated over. The ‘%’ modulus operator is used to find the prime numbers. Below is a demonstration of the same lower_range = 670 upper_range = 699 print("The lower and upper range are :") print(lower_range, upper_range) print("The prime numbers between", lower_range, "and", upper_range, "are:") for num in range(lower_range, upper_range + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) The lower and upper range are : 670 699 The prime numbers between 670 and 699 are: 673 677 683 691 The upper range and lower range values are entered and displayed on the console. The upper range and lower range values are entered and displayed on the console. The numbers are iterated over. The numbers are iterated over. It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number. It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number. The numbers are iterated, and ‘%’ with 2. The numbers are iterated, and ‘%’ with 2. This way the prime number is found, and displayed on console. This way the prime number is found, and displayed on console. Else it breaks out of the loop. Else it breaks out of the loop.
[ { "code": null, "e": 1247, "s": 1062, "text": "When it is required to find the prime numbers within a given range of numbers, the range is entered and it is iterated over. The ‘%’ modulus operator is used to find the prime numbers." }, { "code": null, "e": 1284, "s": 1247, "text": "Below is a demonstration of the same" }, { "code": null, "e": 1640, "s": 1284, "text": "lower_range = 670\nupper_range = 699\nprint(\"The lower and upper range are :\")\nprint(lower_range, upper_range)\nprint(\"The prime numbers between\", lower_range, \"and\", upper_range, \"are:\")\nfor num in range(lower_range, upper_range + 1):\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n break\n else:\n print(num)" }, { "code": null, "e": 1739, "s": 1640, "text": "The lower and upper range are :\n670 699\nThe prime numbers between 670 and 699 are:\n673\n677\n683\n691" }, { "code": null, "e": 1820, "s": 1739, "text": "The upper range and lower range values are entered and displayed on the console." }, { "code": null, "e": 1901, "s": 1820, "text": "The upper range and lower range values are entered and displayed on the console." }, { "code": null, "e": 1932, "s": 1901, "text": "The numbers are iterated over." }, { "code": null, "e": 1963, "s": 1932, "text": "The numbers are iterated over." }, { "code": null, "e": 2069, "s": 1963, "text": "It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number." }, { "code": null, "e": 2175, "s": 2069, "text": "It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number." }, { "code": null, "e": 2217, "s": 2175, "text": "The numbers are iterated, and ‘%’ with 2." }, { "code": null, "e": 2259, "s": 2217, "text": "The numbers are iterated, and ‘%’ with 2." }, { "code": null, "e": 2321, "s": 2259, "text": "This way the prime number is found, and displayed on console." }, { "code": null, "e": 2383, "s": 2321, "text": "This way the prime number is found, and displayed on console." }, { "code": null, "e": 2415, "s": 2383, "text": "Else it breaks out of the loop." }, { "code": null, "e": 2447, "s": 2415, "text": "Else it breaks out of the loop." } ]
Create a directory in Java
A directory can be created with the required abstract path name using the method java.io.File.mkdir(). This method requires no parameters and it returns true on the success of the directory creation or false otherwise. A program that demonstrates this is given as follows − Live Demo import java.io.File; public class Demo { public static void main(String[] args) { try { File file = new File("c:\\demo1\\"); file.createNewFile(); boolean flag = file.mkdir(); System.out.print("Directory created? " + flag); } catch(Exception e) { e.printStackTrace(); } } } The output of the above program is as follows − Directory created? false Note − The output may vary on Online Compilers. Now let us understand the above program. The method java.io.File.mkdir() is used to create a directory in Java. Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows − try { File file = new File("c:\\demo1\\"); file.createNewFile(); boolean flag = file.mkdir(); System.out.print("Directory created? " + flag); } catch(Exception e) { e.printStackTrace(); }
[ { "code": null, "e": 1281, "s": 1062, "text": "A directory can be created with the required abstract path name using the method java.io.File.mkdir(). This method requires no parameters and it returns true on the success of the directory creation or false otherwise." }, { "code": null, "e": 1336, "s": 1281, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1347, "s": 1336, "text": " Live Demo" }, { "code": null, "e": 1690, "s": 1347, "text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n try {\n File file = new File(\"c:\\\\demo1\\\\\");\n file.createNewFile();\n boolean flag = file.mkdir();\n System.out.print(\"Directory created? \" + flag);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 1738, "s": 1690, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1763, "s": 1738, "text": "Directory created? false" }, { "code": null, "e": 1811, "s": 1763, "text": "Note − The output may vary on Online Compilers." }, { "code": null, "e": 1852, "s": 1811, "text": "Now let us understand the above program." }, { "code": null, "e": 2042, "s": 1852, "text": "The method java.io.File.mkdir() is used to create a directory in Java. Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2245, "s": 2042, "text": "try {\n File file = new File(\"c:\\\\demo1\\\\\");\n file.createNewFile();\n boolean flag = file.mkdir();\n System.out.print(\"Directory created? \" + flag);\n} catch(Exception e) {\n e.printStackTrace();\n}" } ]
Deep Learning for Self-Driving Cars | by Manajit Pal | Towards Data Science
Thanks a lot to Valohai for using my rusty tutorial as an intro to their awesome machine learning platform 😍. I would suggest you all to check out their example on how to train the network on the cloud with full version control by using the Valohai machine learning platform (www.valohai.com). We all know self-driving cars is one of the hottest areas of research and business for the tech giants. What seemed like a science-fiction, a few years ago, now seems more like something which is soon to become a part and parcel of life. The reason, I am saying “soon to be” is because of the fact that even though companies like Tesla, Nissan, Cadillac do have self-driving car assistance software, but, they still require a human to keep an eye on the road and take control when needed. However, it is fascinating to see how far we have come in terms of innovation and how fast technology is advancing. So much so, that now, with the help of basic deep learning, neural network magic, we can build our own pipeline for autonomous driving! Excited? I sure am! Let’s get right into it then... Prerequisites:1. This article assumes a basic understanding of Convolutional Neural Networks and its working.2. The code mentioned here is written in Python using the Pytorch framework so basic knowledge of the language and the framework is recommended. If the above seems gibberish to you, do not panic! This free course by Udacity will give you everything you need to know about the basics of Deep Learning and Pytorch. My Background I started my deep learning journey with one of the Udacity’s scholarship programme sponsored by Facebook through which I learned the basics of Pytorch from the course mentioned above. Simultaneously, I was also enrolled in Udacity’s Self-Driving Car Engineer Nanodegree programme sponsored by KPIT where I got to code an end-to-end deep learning model for a self-driving car in Keras as one of my projects. Therefore, I decided to rewrite the code in Pytorch and share the stuff I learned in this process. Okay, enough of me talking, let’s set up our machine for the awesomeness with one thing in mind — Say NO to overfitting! Resources for the Project1. Udacity’s self-driving car simulator2. Of course, Python and the Pytorch Framework3. If your machine does not support GPU, then I would recommend using Google Colab to train your network. It provides GPU and TPU hours for free!4. If you are facing problems gathering your training data, you can use the one provided by Udacity to train your network.5. The complete code is available here and the Colab notebook is available here.6. The Nvidia research paper mentioned in this article can be found here. Gathering DataThe Udacity provided dataset works well but it is not enough to get the car running in difficult terrain (like the second track in Udacity simulator). To gather the data from track 2, we would first need to create a folder in our project directory. Let’s call this folder- data. Now, fire up our simulator. Select the second track from the menu and go to the training mode option. Once you enter the training mode, you shall see a record option on the top right corner of the screen. Click on the icon and browse to the data folder. Press select. You can start recording your ride once you press the record icon again! Now, if you are a novice gamer like me, I would suggest to take things slow and try to make sure your car stays at the center of the road as much possible, even during the turns. This would help to get better training data that will eventually make a good model. We will record 2 laps driving in one direction of the track and also 2 more laps driving in the opposite direction to make sure the turns are reversed. This would make sure our model does not overfit and make better left and right turns. Let’s do it! The training data is now stored in the data folder. Inside, there is one folder and one file: IMG and driving_log.csv. Our next job is to read from the CSV file, the names of the images and their related steering data and load the respective image from the IMG folder in Python. TIME TO CODE! It would be better to work with Colab if you prefer not taking the headache of installing different libraries and frameworks in your local machine and also if you would like to take advantage of the free GPU hours. Also, if you prefer not collecting data then you can import the Udacity’s dataset using !wget URL and unzip the file using !unzip. First thing’s first. Importing the headers: Reading and splitting the data The code above reads everything from the log file and stores it into the sample array. The line next(reader, None) takes away the first row which contains the names of the columns. We shall use this array to split our data into training and validation. One Good practice from what I have learned is to have 20–30% of training data as the validation set to compare the validation loss and training loss so that we can avoid overfitting. Let’s do that: Loading Images in DataloaderNow that we have made the samples, it is time to read the images and augment them. This is an important step as this will help to generalize our model. But the process is computationally heavy and time-consuming even for GPUs. The trick is to parallelize this process by taking data in batches, augmenting them and sending to the model to train. Keras achieves this process using python generators and the fit_generator function. In Pytorch, we shall use the Dataset class and the Dataloader function to achieve this. In order to implement this, we would have to overload a few functions of the class, namely, the __getitem__, __len__ and __init__ functions. We would also have to define some augmenting processes. I coded a basic function that will take an image and randomly crop it and flip it horizontally along with taking the negative of the steering data. The cropping, basically, helps the model to focus only on the road by taking away the sky and other distracting stuff in the image and flipping is done to make sure the images are generalized to left and right turns, essentially keeping the car at the center of the road. Other techniques could be adding random brightness to imitate different duration of the day, overlaying the image with a layer of distortion and noise to simulate rain, adding random shadows on the road etc. But we will just stick to the basics for now. Next up, we define the Dataloader class and pass on this augment function to the input batch samples, concatenate the steering data and images and return it. Notice that there is also an argument called transform. Our transformation will normalize the image array values to the range 0–1 using a lambda function. Next, we use Dataloader function to add everything in a generator that will be called batch-wise during training. We define a batch size of 32 and shuffle them while passing it to the DataLoader. The num_workers defines how many workers will create the batches in parallel for processing. Model ArchitectureIt is time to build our model. Let’s look closely at the Nvidia research paper. Go ahead and open it in a new tab. The link is on the resources section above. If you scroll down to page 5 of the pdf, you will see the architecture of the CNN they built. Okay, you lazy person, this is the image I am talking about 😝. If you look at the numbers, you shall see the depth of the convolutional layers and the input and output features of the fully-connected layers. Now, every feature maps have some mentioned kernels going over them. As mentioned in the paper, the Nvidia guys used YUV images as input and used strided convolutions in the first three convolutional layers with a 2×2 stride and a 5×5 kernel and a non-strided convolution with a 3×3 kernel size in the last two convolutional layers. Interestingly, however, there was no mention of maxpool layer. I tried to follow the above architecture religiously and build the CNN. Here is what I came up with: Unfortunately, something was wrong with this approach. Maybe it was a lack of data or maybe the absence of maxpool layers, the network performed horribly. The car was always drifting off road even on a straight track. After some Google search, I came across this repo. The model used here as a simplified version of the Nvidia architecture. I tried and it worked perfectly when trained with enough epochs. So the final architecture for me was this: However, feel free to try out the first model with maxpool layers. It shall require some calculation for padding and the output height and width. Let’s take a moment to look over a few things here- a) nn.Module- The nn.Module class is used in Pytorch to create a CNN. We have to overload the __init__() and forward() functions to build the network. I made use of nn.Sequential() in order to avoid writing duplicate code. Whatever is in the nn.Sequential() function gets applied to the input sequentially. Pretty neat, eh?a) elu activation- The activation function used here is elu (exponential linear unit). Unlike relu (rectified linear unit), elu speeds up the training process and also solves the vanishing gradient problem. More details and the equation of the elu function can be found here.b) Image Flattening- The flattening of the output from convolutional layers before passing to the fully-connected layers is done with the line: output.view(output.size(0), -1) . Optimizer and CriterionMoving on, the paper also discusses using Mean Square Error loss as the criterion and an Adam optimizer. Let’s code that out! I set the learning rate to 0.0001. You can adjust it accordingly. Hmm, we are getting somewhere here. Before we code the final training and validation parts, let’s venture into the world of GPUs! Pytorch and CUDAPytorch provides an easy integration with CUDA enabled GPUs (sorry AMD). This is done with a simple device() function. It can immensely speed up the training process, like 10x faster than a normal CPU. Why not take advantage of this? For that, we need to transfer our data and the model to GPU for processing. It is really easier than it sounds. We define a function that will do this for all the input it receives. Notice, that I have converted it to float() so that model is able to compute the inputs. TrainingTime to train our masterpiece! We first transfer the model to GPU, then, use the generator to get our data and that to the GPU as well. Next, we set the optimizer to not accumulate the gradients during backpropagation using the optimizer.zero_grad() function. Finally, we calculate the total train loss and divide by the batch size to the get the average training loss per epoch. Pretty straightforward. ValidationSame thing for validation, but this time we will make sure our model is in evaluation mode so that we do not mistakenly update the gradients and backpropagate the errors. We use model.eval() for changing the mode and to make sure the model does not track we use torch.set_grad_enabled(False). The loss is calculated in the same way. Saving the ModelThe final step of the code is here! After the training is complete, we save the model to use it for driving the car autonomously in our simulator. We make a state dictionary and save the model with .h5 format using torch.save(). The Fun Stuff BeginsOne final thing before we begin testing our model, we need a file that will load our model, get the frames of the track from the simulator to process through our model and send the steering prediction back to the simulator. Fear not! I have made a drive.py file which basically a Pytorch version of Udacity’s drive.py file I used in my project. You can go through the code and experiment with it if you want different throttle etc. For now, let’s get copy-paste the content of the below code. github.com Also, we would need a model.py file which shall contain the model architecture. Create the file and paste your network architecture. If you face any problem, feel free to take a look at my model.py file in the repo. Download the model.h5 file in the same directory if you had been using Google Colab to write your code. Fire up the terminal, cd to your directory and run the script with our model: python drive.py model.h5 If you have two different python version installed in your machine, use python3 instead of python. Click on allow, when you see any popups. Open the simulator again and now choose the autonomous mode. The car should drive on its own like a boss! There you go! Your very own self-driving car pipeline. How cool is that! 😁 Here is a little demo of what you might expect: TroubleshootingYou might see the car wobble a lot or maybe it is confined to one side of the road. This might mean that the data is not augmented and generalized properly. Try to acquire more training data or augment with more randomness. You might also see the car not moving at all. In that case, check the terminal for any errors during the run. Most of the errors should be solved by installing the appropriate dependency of the library. ConclusionThanks a lot for taking the time to read my article. I really hope that this helps someone who wants to learn some concepts about the use of Deep learning in self-driving cars. Also, this is my first article related to AI and I am a total beginner so I would really appreciate if you could take some to leave any positive or negative feedback, your thoughts or other resources that you might think is a better way to build AI for self-driving cars in the comments below. Cheers folks!
[ { "code": null, "e": 465, "s": 171, "text": "Thanks a lot to Valohai for using my rusty tutorial as an intro to their awesome machine learning platform 😍. I would suggest you all to check out their example on how to train the network on the cloud with full version control by using the Valohai machine learning platform (www.valohai.com)." }, { "code": null, "e": 1258, "s": 465, "text": "We all know self-driving cars is one of the hottest areas of research and business for the tech giants. What seemed like a science-fiction, a few years ago, now seems more like something which is soon to become a part and parcel of life. The reason, I am saying “soon to be” is because of the fact that even though companies like Tesla, Nissan, Cadillac do have self-driving car assistance software, but, they still require a human to keep an eye on the road and take control when needed. However, it is fascinating to see how far we have come in terms of innovation and how fast technology is advancing. So much so, that now, with the help of basic deep learning, neural network magic, we can build our own pipeline for autonomous driving! Excited? I sure am! Let’s get right into it then..." }, { "code": null, "e": 1512, "s": 1258, "text": "Prerequisites:1. This article assumes a basic understanding of Convolutional Neural Networks and its working.2. The code mentioned here is written in Python using the Pytorch framework so basic knowledge of the language and the framework is recommended." }, { "code": null, "e": 1680, "s": 1512, "text": "If the above seems gibberish to you, do not panic! This free course by Udacity will give you everything you need to know about the basics of Deep Learning and Pytorch." }, { "code": null, "e": 2321, "s": 1680, "text": "My Background I started my deep learning journey with one of the Udacity’s scholarship programme sponsored by Facebook through which I learned the basics of Pytorch from the course mentioned above. Simultaneously, I was also enrolled in Udacity’s Self-Driving Car Engineer Nanodegree programme sponsored by KPIT where I got to code an end-to-end deep learning model for a self-driving car in Keras as one of my projects. Therefore, I decided to rewrite the code in Pytorch and share the stuff I learned in this process. Okay, enough of me talking, let’s set up our machine for the awesomeness with one thing in mind — Say NO to overfitting!" }, { "code": null, "e": 2852, "s": 2321, "text": "Resources for the Project1. Udacity’s self-driving car simulator2. Of course, Python and the Pytorch Framework3. If your machine does not support GPU, then I would recommend using Google Colab to train your network. It provides GPU and TPU hours for free!4. If you are facing problems gathering your training data, you can use the one provided by Udacity to train your network.5. The complete code is available here and the Colab notebook is available here.6. The Nvidia research paper mentioned in this article can be found here." }, { "code": null, "e": 3247, "s": 2852, "text": "Gathering DataThe Udacity provided dataset works well but it is not enough to get the car running in difficult terrain (like the second track in Udacity simulator). To gather the data from track 2, we would first need to create a folder in our project directory. Let’s call this folder- data. Now, fire up our simulator. Select the second track from the menu and go to the training mode option." }, { "code": null, "e": 3413, "s": 3247, "text": "Once you enter the training mode, you shall see a record option on the top right corner of the screen. Click on the icon and browse to the data folder. Press select." }, { "code": null, "e": 3999, "s": 3413, "text": "You can start recording your ride once you press the record icon again! Now, if you are a novice gamer like me, I would suggest to take things slow and try to make sure your car stays at the center of the road as much possible, even during the turns. This would help to get better training data that will eventually make a good model. We will record 2 laps driving in one direction of the track and also 2 more laps driving in the opposite direction to make sure the turns are reversed. This would make sure our model does not overfit and make better left and right turns. Let’s do it!" }, { "code": null, "e": 4278, "s": 3999, "text": "The training data is now stored in the data folder. Inside, there is one folder and one file: IMG and driving_log.csv. Our next job is to read from the CSV file, the names of the images and their related steering data and load the respective image from the IMG folder in Python." }, { "code": null, "e": 4292, "s": 4278, "text": "TIME TO CODE!" }, { "code": null, "e": 4682, "s": 4292, "text": "It would be better to work with Colab if you prefer not taking the headache of installing different libraries and frameworks in your local machine and also if you would like to take advantage of the free GPU hours. Also, if you prefer not collecting data then you can import the Udacity’s dataset using !wget URL and unzip the file using !unzip. First thing’s first. Importing the headers:" }, { "code": null, "e": 4713, "s": 4682, "text": "Reading and splitting the data" }, { "code": null, "e": 5164, "s": 4713, "text": "The code above reads everything from the log file and stores it into the sample array. The line next(reader, None) takes away the first row which contains the names of the columns. We shall use this array to split our data into training and validation. One Good practice from what I have learned is to have 20–30% of training data as the validation set to compare the validation loss and training loss so that we can avoid overfitting. Let’s do that:" }, { "code": null, "e": 6581, "s": 5164, "text": "Loading Images in DataloaderNow that we have made the samples, it is time to read the images and augment them. This is an important step as this will help to generalize our model. But the process is computationally heavy and time-consuming even for GPUs. The trick is to parallelize this process by taking data in batches, augmenting them and sending to the model to train. Keras achieves this process using python generators and the fit_generator function. In Pytorch, we shall use the Dataset class and the Dataloader function to achieve this. In order to implement this, we would have to overload a few functions of the class, namely, the __getitem__, __len__ and __init__ functions. We would also have to define some augmenting processes. I coded a basic function that will take an image and randomly crop it and flip it horizontally along with taking the negative of the steering data. The cropping, basically, helps the model to focus only on the road by taking away the sky and other distracting stuff in the image and flipping is done to make sure the images are generalized to left and right turns, essentially keeping the car at the center of the road. Other techniques could be adding random brightness to imitate different duration of the day, overlaying the image with a layer of distortion and noise to simulate rain, adding random shadows on the road etc. But we will just stick to the basics for now." }, { "code": null, "e": 6739, "s": 6581, "text": "Next up, we define the Dataloader class and pass on this augment function to the input batch samples, concatenate the steering data and images and return it." }, { "code": null, "e": 7183, "s": 6739, "text": "Notice that there is also an argument called transform. Our transformation will normalize the image array values to the range 0–1 using a lambda function. Next, we use Dataloader function to add everything in a generator that will be called batch-wise during training. We define a batch size of 32 and shuffle them while passing it to the DataLoader. The num_workers defines how many workers will create the batches in parallel for processing." }, { "code": null, "e": 7360, "s": 7183, "text": "Model ArchitectureIt is time to build our model. Let’s look closely at the Nvidia research paper. Go ahead and open it in a new tab. The link is on the resources section above." }, { "code": null, "e": 7454, "s": 7360, "text": "If you scroll down to page 5 of the pdf, you will see the architecture of the CNN they built." }, { "code": null, "e": 8159, "s": 7454, "text": "Okay, you lazy person, this is the image I am talking about 😝. If you look at the numbers, you shall see the depth of the convolutional layers and the input and output features of the fully-connected layers. Now, every feature maps have some mentioned kernels going over them. As mentioned in the paper, the Nvidia guys used YUV images as input and used strided convolutions in the first three convolutional layers with a 2×2 stride and a 5×5 kernel and a non-strided convolution with a 3×3 kernel size in the last two convolutional layers. Interestingly, however, there was no mention of maxpool layer. I tried to follow the above architecture religiously and build the CNN. Here is what I came up with:" }, { "code": null, "e": 8608, "s": 8159, "text": "Unfortunately, something was wrong with this approach. Maybe it was a lack of data or maybe the absence of maxpool layers, the network performed horribly. The car was always drifting off road even on a straight track. After some Google search, I came across this repo. The model used here as a simplified version of the Nvidia architecture. I tried and it worked perfectly when trained with enough epochs. So the final architecture for me was this:" }, { "code": null, "e": 9582, "s": 8608, "text": "However, feel free to try out the first model with maxpool layers. It shall require some calculation for padding and the output height and width. Let’s take a moment to look over a few things here- a) nn.Module- The nn.Module class is used in Pytorch to create a CNN. We have to overload the __init__() and forward() functions to build the network. I made use of nn.Sequential() in order to avoid writing duplicate code. Whatever is in the nn.Sequential() function gets applied to the input sequentially. Pretty neat, eh?a) elu activation- The activation function used here is elu (exponential linear unit). Unlike relu (rectified linear unit), elu speeds up the training process and also solves the vanishing gradient problem. More details and the equation of the elu function can be found here.b) Image Flattening- The flattening of the output from convolutional layers before passing to the fully-connected layers is done with the line: output.view(output.size(0), -1) ." }, { "code": null, "e": 9797, "s": 9582, "text": "Optimizer and CriterionMoving on, the paper also discusses using Mean Square Error loss as the criterion and an Adam optimizer. Let’s code that out! I set the learning rate to 0.0001. You can adjust it accordingly." }, { "code": null, "e": 9927, "s": 9797, "text": "Hmm, we are getting somewhere here. Before we code the final training and validation parts, let’s venture into the world of GPUs!" }, { "code": null, "e": 10359, "s": 9927, "text": "Pytorch and CUDAPytorch provides an easy integration with CUDA enabled GPUs (sorry AMD). This is done with a simple device() function. It can immensely speed up the training process, like 10x faster than a normal CPU. Why not take advantage of this? For that, we need to transfer our data and the model to GPU for processing. It is really easier than it sounds. We define a function that will do this for all the input it receives." }, { "code": null, "e": 10448, "s": 10359, "text": "Notice, that I have converted it to float() so that model is able to compute the inputs." }, { "code": null, "e": 10860, "s": 10448, "text": "TrainingTime to train our masterpiece! We first transfer the model to GPU, then, use the generator to get our data and that to the GPU as well. Next, we set the optimizer to not accumulate the gradients during backpropagation using the optimizer.zero_grad() function. Finally, we calculate the total train loss and divide by the batch size to the get the average training loss per epoch. Pretty straightforward." }, { "code": null, "e": 11203, "s": 10860, "text": "ValidationSame thing for validation, but this time we will make sure our model is in evaluation mode so that we do not mistakenly update the gradients and backpropagate the errors. We use model.eval() for changing the mode and to make sure the model does not track we use torch.set_grad_enabled(False). The loss is calculated in the same way." }, { "code": null, "e": 11448, "s": 11203, "text": "Saving the ModelThe final step of the code is here! After the training is complete, we save the model to use it for driving the car autonomously in our simulator. We make a state dictionary and save the model with .h5 format using torch.save()." }, { "code": null, "e": 11961, "s": 11448, "text": "The Fun Stuff BeginsOne final thing before we begin testing our model, we need a file that will load our model, get the frames of the track from the simulator to process through our model and send the steering prediction back to the simulator. Fear not! I have made a drive.py file which basically a Pytorch version of Udacity’s drive.py file I used in my project. You can go through the code and experiment with it if you want different throttle etc. For now, let’s get copy-paste the content of the below code." }, { "code": null, "e": 11972, "s": 11961, "text": "github.com" }, { "code": null, "e": 12188, "s": 11972, "text": "Also, we would need a model.py file which shall contain the model architecture. Create the file and paste your network architecture. If you face any problem, feel free to take a look at my model.py file in the repo." }, { "code": null, "e": 12370, "s": 12188, "text": "Download the model.h5 file in the same directory if you had been using Google Colab to write your code. Fire up the terminal, cd to your directory and run the script with our model:" }, { "code": null, "e": 12396, "s": 12370, "text": "python drive.py model.h5 " }, { "code": null, "e": 12536, "s": 12396, "text": "If you have two different python version installed in your machine, use python3 instead of python. Click on allow, when you see any popups." }, { "code": null, "e": 12642, "s": 12536, "text": "Open the simulator again and now choose the autonomous mode. The car should drive on its own like a boss!" }, { "code": null, "e": 12717, "s": 12642, "text": "There you go! Your very own self-driving car pipeline. How cool is that! 😁" }, { "code": null, "e": 12765, "s": 12717, "text": "Here is a little demo of what you might expect:" }, { "code": null, "e": 13004, "s": 12765, "text": "TroubleshootingYou might see the car wobble a lot or maybe it is confined to one side of the road. This might mean that the data is not augmented and generalized properly. Try to acquire more training data or augment with more randomness." }, { "code": null, "e": 13207, "s": 13004, "text": "You might also see the car not moving at all. In that case, check the terminal for any errors during the run. Most of the errors should be solved by installing the appropriate dependency of the library." } ]
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks
28 Jun, 2021 In a binary tree with n nodes, every node has an odd number of descendants. Every node is considered to be its own descendant. What is the number of nodes in the tree that have exactly one child?(A) 0(B) 1(C) (n-1)/2(D) n-1Answer: (A)Explanation: It is mentioned that each node has odd number of descendants including node itself, so all nodes must have even number of descendants 0, 2, 4 so on. Which means each node should have either 0 or 2 children. So there will be no node with 1 child. Hence 0 is answer. Following are few examples. a / \ b c a / \ b c / \ d e Such a binary tree is full binary tree (a binary tree where every node has 0 or 2 children).Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE CS 2019 | Question 37 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24446, "s": 24418, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24958, "s": 24446, "text": "In a binary tree with n nodes, every node has an odd number of descendants. Every node is considered to be its own descendant. What is the number of nodes in the tree that have exactly one child?(A) 0(B) 1(C) (n-1)/2(D) n-1Answer: (A)Explanation: It is mentioned that each node has odd number of descendants including node itself, so all nodes must have even number of descendants 0, 2, 4 so on. Which means each node should have either 0 or 2 children. So there will be no node with 1 child. Hence 0 is answer." }, { "code": null, "e": 24986, "s": 24958, "text": "Following are few examples." }, { "code": null, "e": 25066, "s": 24986, "text": " a\n / \\\n b c\n\n\n a\n / \\\n b c \n / \\\n d e" }, { "code": null, "e": 25180, "s": 25066, "text": "Such a binary tree is full binary tree (a binary tree where every node has 0 or 2 children).Quiz of this Question" }, { "code": null, "e": 25193, "s": 25180, "text": "GATE-CS-2010" }, { "code": null, "e": 25211, "s": 25193, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 25216, "s": 25211, "text": "GATE" }, { "code": null, "e": 25314, "s": 25216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25323, "s": 25314, "text": "Comments" }, { "code": null, "e": 25336, "s": 25323, "text": "Old Comments" }, { "code": null, "e": 25370, "s": 25336, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25412, "s": 25370, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25446, "s": 25412, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25488, "s": 25446, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25530, "s": 25488, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 25572, "s": 25530, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25614, "s": 25572, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25648, "s": 25614, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 25682, "s": 25648, "text": "GATE | GATE CS 2019 | Question 37" } ]
Using Docopt in python, the most user-friendly command-line parsing library | by Jonathan Leban | Towards Data Science
When you work on file which deals with many arguments, it is time consuming and not user friendly to always change those arguments inside the python file. Some libraries have been implemented to solve this problem, known as command line parsing library. In python, they are three different solutions: Docopt, Argparse and Click. In this article I will go in depth in the use of Docopt and not Argparse or Click. I made this choice because after having used all those three methods, I realized that Docopt is by far the most user-friendly way to parse arguments into a file. The way I will present the Docopt library is by showing you an example of a docopt.py file with the setup.py and requirements.txt file that go with it. ### docopt.py file '''Usage:docopt.py square [options] [operation] [square-option]docopt.py rectangle [options] [operation] [triangle-option]operation: --area=<bool> Calculate the area if the argument==True --perimeter=<bool> Calculate the perimeter if the argument==Truesquare-option: --edge=<float> Edge of the square. [default: 2]rectangle-option: --height=<float> Height of the rectangle --width=<float> Width of the rectangle '''from docopt import docoptdef area(args): """ This method computes the area of a square or a rectangle """ if bool(args['square']): if args['--edge']: area = float(args['edge']) ** 2 else: print("You must specify the edge") elif bool(args['rectangle']): if args['--height'] and args['--width']: area = float(args['--height']) * float(args['--width']) else: print("You have forgotten to specify either the height or the width or both") return areadef perimeter(args): """ This method computes the perimeter of a square or a rectangle """ if bool(args['square']): if args['--edge']: perimeter = float(args['edge']) * 2 else: print("You must specify the edge") elif bool(args['rectangle']): if args['--height'] and args['--width']: perimeter = float(args['--height']) + float(args['--width']) else: print("You have forgotten to specify either the height or the width or both") return perimeterdef main(): args = docopt(__doc__) if args['--area']: area(args) elif args['--perimeter']: perimeter(args) else: print("command not found")if __name__=='__main__': main() They are two parts in the docopt.py file: the definition of the arguments in the docString the different methods you want/need to call In the Usage part you write what will be the calling format of your command line in your terminal. Thus, if I want to call the area operation on a square of edge 5, I will do the following.: python -m docopt.py square --area=True --edge=5 As you can see that in the “Usage” part, we can define default values but these values will be overwritten if we specify a value in the command line like we did with the “ — edge” argument. So let’s decompose the command line: docopt.py : is the name of the python file that you want to run square or rectangle are two necessary arguments that we need to give in the command line to run it properly [options]: is a necessary bracket argument announcing that the following elements will be optional arguments [operation]: it is composed by two different arguments which are “ — area” and “ — perimeter”. For these two parameters, the value we need to enter in the command line is a boolean. The ‘=<bool>’ is optional but gives a hint of what kind of element the user needs to enter. [square-option]: it is composed by one argument with a default value In this part, I will go through the methods ‘area’ and ‘perimeter’ . But before doing so, you notice that you need to import the docopt package and before it you need to install it. However, for the moment forget about the installation, I will give you a clean way to do it after. You notice that in both methods, when I need an argument from docopt I need to convert it into its proper type. For example args[‘square’] is a boolean but I need to explicitly convert it as a boolean. Then, the methods for computing the area and the perimeter are pretty basic methods but are optional methods. Nevertheless, there are two lines at the end of the file which are necessary to run the file properly: if __name__=='__main__': main() Now that we have created our docopt.py file, we can create a setup.py file as long as a requirements.txt file to make our project even more user-friendly. A setup.py file is a python file where you describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing. In this file you can specify which files in your project you want to run and which are the packages required to run the project. Before diving into the setup.py file you need to have the following architecture in your project: /docopt-demo docopt.py requirements.txt setup.py Here is an example of a setup.py file you can write regarding this project: ### setup.py file from setuptools import setupwith open("requirements.txt", "r") as fh: requirements = fh.readlines()setup( name = 'docopt-demo', author = 'JonathanL', description = 'Example of the setup file for the docopt demo', version = '0.1.0', packages = ['docopt-demo'], install_requires = [req for req in requirements if req[:2] != "# "], include_package_data=True, entry_points = { 'console_scripts': [ 'docopt = docopt-demo.docopt:main' ] }) And here is the requirements.txt file: # Argument parser packagesdocopt==0.6.2 The first element you have to do it to import setup from setuptools but this package goes with python so if you have python on your computer will have it. Then, you need to create a list of all the required packages you will parse in the install_requires argument in the setup module. In the setup module there are some elements you need to be aware of: packages: should have the same name as the folder you are in so for us it is ‘docopt-demo’ in the ‘console_script’ you can specify a short cut for a specific file. In our case, instead of typing in the terminal : python -m docopt square --area=True --edge=5 We will just have to enter: docopt square --area=True --edge=5 In fact, we associate the word ‘docopt’ to the operation ‘docopt-demo.docopt:main’ which is launching the main function in the docopt.py file. In this file you specify all the packages you need to install to run your project properly. You have two choices to specify the version: either you tell the exact version you want to use and you will use the ‘==’ sign or you can also use operators like ‘>=’ to specify an older version of the package In this article, I show how to use the Docopt python package which is a very nice way to parse arguments into a file. I hope you found what you came here for in this article and stay with me for the next episodes of this image recognition trip! PS: I am currently a Machine Learning Engineer at Unity Technologies recently graduated from a Master of Engineering at UC Berkeley, and if you want to discuss the topic, feel free to reach me. Here is my email.
[ { "code": null, "e": 501, "s": 172, "text": "When you work on file which deals with many arguments, it is time consuming and not user friendly to always change those arguments inside the python file. Some libraries have been implemented to solve this problem, known as command line parsing library. In python, they are three different solutions: Docopt, Argparse and Click." }, { "code": null, "e": 746, "s": 501, "text": "In this article I will go in depth in the use of Docopt and not Argparse or Click. I made this choice because after having used all those three methods, I realized that Docopt is by far the most user-friendly way to parse arguments into a file." }, { "code": null, "e": 898, "s": 746, "text": "The way I will present the Docopt library is by showing you an example of a docopt.py file with the setup.py and requirements.txt file that go with it." }, { "code": null, "e": 2592, "s": 898, "text": "### docopt.py file '''Usage:docopt.py square [options] [operation] [square-option]docopt.py rectangle [options] [operation] [triangle-option]operation: --area=<bool> Calculate the area if the argument==True --perimeter=<bool> Calculate the perimeter if the argument==Truesquare-option: --edge=<float> Edge of the square. [default: 2]rectangle-option: --height=<float> Height of the rectangle --width=<float> Width of the rectangle '''from docopt import docoptdef area(args): \"\"\" This method computes the area of a square or a rectangle \"\"\" if bool(args['square']): if args['--edge']: area = float(args['edge']) ** 2 else: print(\"You must specify the edge\") elif bool(args['rectangle']): if args['--height'] and args['--width']: area = float(args['--height']) * float(args['--width']) else: print(\"You have forgotten to specify either the height or the width or both\") return areadef perimeter(args): \"\"\" This method computes the perimeter of a square or a rectangle \"\"\" if bool(args['square']): if args['--edge']: perimeter = float(args['edge']) * 2 else: print(\"You must specify the edge\") elif bool(args['rectangle']): if args['--height'] and args['--width']: perimeter = float(args['--height']) + float(args['--width']) else: print(\"You have forgotten to specify either the height or the width or both\") return perimeterdef main(): args = docopt(__doc__) if args['--area']: area(args) elif args['--perimeter']: perimeter(args) else: print(\"command not found\")if __name__=='__main__': main()" }, { "code": null, "e": 2634, "s": 2592, "text": "They are two parts in the docopt.py file:" }, { "code": null, "e": 2683, "s": 2634, "text": "the definition of the arguments in the docString" }, { "code": null, "e": 2727, "s": 2683, "text": "the different methods you want/need to call" }, { "code": null, "e": 2918, "s": 2727, "text": "In the Usage part you write what will be the calling format of your command line in your terminal. Thus, if I want to call the area operation on a square of edge 5, I will do the following.:" }, { "code": null, "e": 2968, "s": 2918, "text": "python -m docopt.py square --area=True --edge=5 " }, { "code": null, "e": 3158, "s": 2968, "text": "As you can see that in the “Usage” part, we can define default values but these values will be overwritten if we specify a value in the command line like we did with the “ — edge” argument." }, { "code": null, "e": 3195, "s": 3158, "text": "So let’s decompose the command line:" }, { "code": null, "e": 3259, "s": 3195, "text": "docopt.py : is the name of the python file that you want to run" }, { "code": null, "e": 3367, "s": 3259, "text": "square or rectangle are two necessary arguments that we need to give in the command line to run it properly" }, { "code": null, "e": 3476, "s": 3367, "text": "[options]: is a necessary bracket argument announcing that the following elements will be optional arguments" }, { "code": null, "e": 3750, "s": 3476, "text": "[operation]: it is composed by two different arguments which are “ — area” and “ — perimeter”. For these two parameters, the value we need to enter in the command line is a boolean. The ‘=<bool>’ is optional but gives a hint of what kind of element the user needs to enter." }, { "code": null, "e": 3819, "s": 3750, "text": "[square-option]: it is composed by one argument with a default value" }, { "code": null, "e": 4100, "s": 3819, "text": "In this part, I will go through the methods ‘area’ and ‘perimeter’ . But before doing so, you notice that you need to import the docopt package and before it you need to install it. However, for the moment forget about the installation, I will give you a clean way to do it after." }, { "code": null, "e": 4302, "s": 4100, "text": "You notice that in both methods, when I need an argument from docopt I need to convert it into its proper type. For example args[‘square’] is a boolean but I need to explicitly convert it as a boolean." }, { "code": null, "e": 4412, "s": 4302, "text": "Then, the methods for computing the area and the perimeter are pretty basic methods but are optional methods." }, { "code": null, "e": 4515, "s": 4412, "text": "Nevertheless, there are two lines at the end of the file which are necessary to run the file properly:" }, { "code": null, "e": 4549, "s": 4515, "text": "if __name__=='__main__': main()" }, { "code": null, "e": 4704, "s": 4549, "text": "Now that we have created our docopt.py file, we can create a setup.py file as long as a requirements.txt file to make our project even more user-friendly." }, { "code": null, "e": 5006, "s": 4704, "text": "A setup.py file is a python file where you describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing. In this file you can specify which files in your project you want to run and which are the packages required to run the project." }, { "code": null, "e": 5104, "s": 5006, "text": "Before diving into the setup.py file you need to have the following architecture in your project:" }, { "code": null, "e": 5159, "s": 5104, "text": "/docopt-demo docopt.py requirements.txt setup.py" }, { "code": null, "e": 5235, "s": 5159, "text": "Here is an example of a setup.py file you can write regarding this project:" }, { "code": null, "e": 5726, "s": 5235, "text": "### setup.py file from setuptools import setupwith open(\"requirements.txt\", \"r\") as fh: requirements = fh.readlines()setup( name = 'docopt-demo', author = 'JonathanL', description = 'Example of the setup file for the docopt demo', version = '0.1.0', packages = ['docopt-demo'], install_requires = [req for req in requirements if req[:2] != \"# \"], include_package_data=True, entry_points = { 'console_scripts': [ 'docopt = docopt-demo.docopt:main' ] })" }, { "code": null, "e": 5765, "s": 5726, "text": "And here is the requirements.txt file:" }, { "code": null, "e": 5805, "s": 5765, "text": "# Argument parser packagesdocopt==0.6.2" }, { "code": null, "e": 5960, "s": 5805, "text": "The first element you have to do it to import setup from setuptools but this package goes with python so if you have python on your computer will have it." }, { "code": null, "e": 6090, "s": 5960, "text": "Then, you need to create a list of all the required packages you will parse in the install_requires argument in the setup module." }, { "code": null, "e": 6159, "s": 6090, "text": "In the setup module there are some elements you need to be aware of:" }, { "code": null, "e": 6250, "s": 6159, "text": "packages: should have the same name as the folder you are in so for us it is ‘docopt-demo’" }, { "code": null, "e": 6372, "s": 6250, "text": "in the ‘console_script’ you can specify a short cut for a specific file. In our case, instead of typing in the terminal :" }, { "code": null, "e": 6417, "s": 6372, "text": "python -m docopt square --area=True --edge=5" }, { "code": null, "e": 6445, "s": 6417, "text": "We will just have to enter:" }, { "code": null, "e": 6480, "s": 6445, "text": "docopt square --area=True --edge=5" }, { "code": null, "e": 6623, "s": 6480, "text": "In fact, we associate the word ‘docopt’ to the operation ‘docopt-demo.docopt:main’ which is launching the main function in the docopt.py file." }, { "code": null, "e": 6715, "s": 6623, "text": "In this file you specify all the packages you need to install to run your project properly." }, { "code": null, "e": 6760, "s": 6715, "text": "You have two choices to specify the version:" }, { "code": null, "e": 6841, "s": 6760, "text": "either you tell the exact version you want to use and you will use the ‘==’ sign" }, { "code": null, "e": 6924, "s": 6841, "text": "or you can also use operators like ‘>=’ to specify an older version of the package" }, { "code": null, "e": 7042, "s": 6924, "text": "In this article, I show how to use the Docopt python package which is a very nice way to parse arguments into a file." }, { "code": null, "e": 7169, "s": 7042, "text": "I hope you found what you came here for in this article and stay with me for the next episodes of this image recognition trip!" } ]
C Program to find transpose of a matrix - GeeksforGeeks
07 Nov, 2018 Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. For Square Matrix : The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. #include <stdio.h>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", B[i][j]); printf("\n"); } return 0;} Result matrix is 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 For Rectangular Matrix : The below program finds transpose of A[][] and stores the result in B[][]. #include <stdio.h>#define M 3#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i];} int main(){ int A[M][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf("%d ", B[i][j]); printf("\n"); } return 0;} Result matrix is 1 2 3 1 2 3 1 2 3 1 2 3 In-Place for Square Matrix: #include <bits/stdc++.h>using namespace std; #define N 4 // Converts A[][] to its transposevoid transpose(int A[][N]){ for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) swap(A[i][j], A[j][i]);} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); printf("Modified matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%d ", A[i][j]); printf("\n"); } return 0;} Modified matrix is 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Please refer complete article on Program to find transpose of a matrix for more details! C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Header files in C/C++ and its uses C Program to read contents of Whole File C program to sort an array in ascending order How to return multiple values from a function in C or C++? Program to print ASCII Value of a character Program to find Prime Numbers Between given Interval Producer Consumer Problem in C How to Append a Character to a String in C C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 C Program to Swap two Numbers
[ { "code": null, "e": 24604, "s": 24576, "text": "\n07 Nov, 2018" }, { "code": null, "e": 24766, "s": 24604, "text": "Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]." }, { "code": null, "e": 24786, "s": 24766, "text": "For Square Matrix :" }, { "code": null, "e": 24902, "s": 24786, "text": "The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension." }, { "code": "#include <stdio.h>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", B[i][j]); printf(\"\\n\"); } return 0;}", "e": 25493, "s": 24902, "text": null }, { "code": null, "e": 25547, "s": 25493, "text": "Result matrix is \n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n1 2 3 4\n" }, { "code": null, "e": 25572, "s": 25547, "text": "For Rectangular Matrix :" }, { "code": null, "e": 25647, "s": 25572, "text": "The below program finds transpose of A[][] and stores the result in B[][]." }, { "code": "#include <stdio.h>#define M 3#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i];} int main(){ int A[M][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf(\"%d \", B[i][j]); printf(\"\\n\"); } return 0;}", "e": 26244, "s": 25647, "text": null }, { "code": null, "e": 26290, "s": 26244, "text": "Result matrix is \n1 2 3 \n1 2 3 \n1 2 3 \n1 2 3\n" }, { "code": null, "e": 26318, "s": 26290, "text": "In-Place for Square Matrix:" }, { "code": "#include <bits/stdc++.h>using namespace std; #define N 4 // Converts A[][] to its transposevoid transpose(int A[][N]){ for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) swap(A[i][j], A[j][i]);} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); printf(\"Modified matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\"%d \", A[i][j]); printf(\"\\n\"); } return 0;}", "e": 26893, "s": 26318, "text": null }, { "code": null, "e": 26949, "s": 26893, "text": "Modified matrix is \n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n1 2 3 4\n" }, { "code": null, "e": 27038, "s": 26949, "text": "Please refer complete article on Program to find transpose of a matrix for more details!" }, { "code": null, "e": 27049, "s": 27038, "text": "C Programs" }, { "code": null, "e": 27147, "s": 27049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27156, "s": 27147, "text": "Comments" }, { "code": null, "e": 27169, "s": 27156, "text": "Old Comments" }, { "code": null, "e": 27204, "s": 27169, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27245, "s": 27204, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27291, "s": 27245, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 27350, "s": 27291, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27394, "s": 27350, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27447, "s": 27394, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 27478, "s": 27447, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27521, "s": 27478, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 27592, "s": 27521, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" } ]
Residual blocks — Building blocks of ResNet | by Sabyasachi Sahoo | Towards Data Science
Understanding a residual block is quite easy. In traditional neural networks, each layer feeds into the next layer. In a network with residual blocks, each layer feeds into the next layer and directly into the layers about 2–3 hops away. That’s it. But understanding the intuition behind why it was required in the first place, why it is so important, and how similar it looks to some other state-of-the-art architectures is where we are going to focus on. There is more than one interpretation of why residual blocks are awesome and how & why they are one of the key ideas that can make a neural network show state-of-the-art performances on a wide range of tasks. Before diving into the details, here is a picture of how a residual block actually looks like. We know neural networks are universal function approximators and that the accuracy increases with increasing the number of layers. But there is a limit to the number of layers added that results in an accuracy improvement. So, if neural networks were universal function approximators, then they should have been able to learn any simplex or complex function. But it turns out that, thanks to some problems like vanishing gradients and the curse of dimensionality, if we have sufficiently deep networks, it may not be able to learn simple functions like an identity function. Now, this is clearly undesirable. Also, if we keep increasing the number of layers, we will see that the accuracy will saturate at one point and eventually degrade. And, this is usually not caused due to overfitting. So, it might seem that the shallower networks are learning better than their deeper counterparts, and this is quite counter-intuitive. But this is what is seen in practice and is popularly known as the degradation problem. Without root causing into the degradation problem and the inability of a deep neural network to learn identity functions, let us start thinking about some possible solutions. In the degradation problem, we know that shallower networks perform better than the deeper counterparts with few more layers added to them. So, why not skip these extra layers and at least match the accuracy of the shallow sub-networks. But, how do you skip layers? You can skip the training of few layers using skip connections or residual connections. This is what we see in the image above. In fact, if you look closely, we can directly learn an identity function by relying on skip connections only. This is the exact reason why skip connections are also called identity shortcut connections too. One solution for all the problems! But why call it residual? Where is the residue? It’s time we let the mathematicians within us come to the surface. Let us consider a neural network block whose input is x, and we would like to learn the true distribution H(x). Let us denote the difference (or the residual) between this as R(x) = Output — Input = H(x) — x Rearranging it, we get, H(x) = R(x) + x Our residual block is overall trying to learn the true output, H(x). If you look closely at the image above, you will realize that since we have an identity connection coming from x, the layers are actually trying to learn the residual, R(x). So to summarize, the layers in a traditional network are learning the true output (H(x)), whereas the layers in a residual network are learning the residual (R(x)). Hence, the name: Residual Block. It has also been observed that it is easier to learn residual of output and input, rather than only the input. As an added advantage, our network can now learn identity function by simply setting residual as zero. And if you truly understand backpropagation and how severe the problem of vanishing gradient becomes with increasing the number of layers, then you can clearly see that because of these skip connections, we can propagate larger gradients to initial layers, and these layers also could learn as fast as the final layers, giving us the ability to train deeper networks. The image below shows how to arrange the residual block and identity connections for the optimal gradient flow. It has been observed that pre-activations with batch normalizations generally give the best results (i.e., the right-most residual block in the image below gives the most promising results). There are even more interpretations of residual blocks and ResNets, other than the ones already discussed above. While training ResNets, we either train the layers in residual blocks or skip the training for those layers using skip connections. So, different parts of networks will be trained at different rates for different training data points based on how the error flows backward in the network. This can be thought of as training an ensemble of different models on the dataset and getting the best possible accuracy. Skipping training in some residual block layers can be looked at from an optimistic point of view too. In general, we do not know the optimal number of layers (or residual blocks) required for a neural network which might depend on the complexity of the dataset. Instead of treating the number of layers as an important hyperparameter to tune, by adding skip connections to our network, we are allowing the network to skip training for the layers that are not useful and do not add value in overall accuracy. In a way, skip connections make our neural networks dynamic to tune the number of layers during training optimally. The image below shows multiple interpretations of a residual block. Let us go a little into the history of skip connections. The idea of skipping connections between the layers was first introduced in Highway Networks. Highway networks had skip connections with gates that controlled how much information is passed through them, and these gates can be trained to open selectively. This idea is also seen in the LSTM networks that control how much information flows from the past data points seen by the network. These gates work similarly to control of memory flow from the previously seen data points. The same idea is shown in the image below. Residual blocks are basically a special case of highway networks without any gates in their skip connections. Essentially, residual blocks allow memory (or information) to flow from initial to last layers. Despite the absence of gates in their skip connections, residual networks perform as well as any other highway network in practice. And before ending this article, below is an image of how the collection of all residual blocks completes into a ResNet. If you are interested in knowing more about ResNet overall and its different variants, check out this article.
[ { "code": null, "e": 933, "s": 172, "text": "Understanding a residual block is quite easy. In traditional neural networks, each layer feeds into the next layer. In a network with residual blocks, each layer feeds into the next layer and directly into the layers about 2–3 hops away. That’s it. But understanding the intuition behind why it was required in the first place, why it is so important, and how similar it looks to some other state-of-the-art architectures is where we are going to focus on. There is more than one interpretation of why residual blocks are awesome and how & why they are one of the key ideas that can make a neural network show state-of-the-art performances on a wide range of tasks. Before diving into the details, here is a picture of how a residual block actually looks like." }, { "code": null, "e": 1542, "s": 933, "text": "We know neural networks are universal function approximators and that the accuracy increases with increasing the number of layers. But there is a limit to the number of layers added that results in an accuracy improvement. So, if neural networks were universal function approximators, then they should have been able to learn any simplex or complex function. But it turns out that, thanks to some problems like vanishing gradients and the curse of dimensionality, if we have sufficiently deep networks, it may not be able to learn simple functions like an identity function. Now, this is clearly undesirable." }, { "code": null, "e": 1948, "s": 1542, "text": "Also, if we keep increasing the number of layers, we will see that the accuracy will saturate at one point and eventually degrade. And, this is usually not caused due to overfitting. So, it might seem that the shallower networks are learning better than their deeper counterparts, and this is quite counter-intuitive. But this is what is seen in practice and is popularly known as the degradation problem." }, { "code": null, "e": 2389, "s": 1948, "text": "Without root causing into the degradation problem and the inability of a deep neural network to learn identity functions, let us start thinking about some possible solutions. In the degradation problem, we know that shallower networks perform better than the deeper counterparts with few more layers added to them. So, why not skip these extra layers and at least match the accuracy of the shallow sub-networks. But, how do you skip layers?" }, { "code": null, "e": 2759, "s": 2389, "text": "You can skip the training of few layers using skip connections or residual connections. This is what we see in the image above. In fact, if you look closely, we can directly learn an identity function by relying on skip connections only. This is the exact reason why skip connections are also called identity shortcut connections too. One solution for all the problems!" }, { "code": null, "e": 3049, "s": 2759, "text": "But why call it residual? Where is the residue? It’s time we let the mathematicians within us come to the surface. Let us consider a neural network block whose input is x, and we would like to learn the true distribution H(x). Let us denote the difference (or the residual) between this as" }, { "code": null, "e": 3082, "s": 3049, "text": "R(x) = Output — Input = H(x) — x" }, { "code": null, "e": 3106, "s": 3082, "text": "Rearranging it, we get," }, { "code": null, "e": 3122, "s": 3106, "text": "H(x) = R(x) + x" }, { "code": null, "e": 3563, "s": 3122, "text": "Our residual block is overall trying to learn the true output, H(x). If you look closely at the image above, you will realize that since we have an identity connection coming from x, the layers are actually trying to learn the residual, R(x). So to summarize, the layers in a traditional network are learning the true output (H(x)), whereas the layers in a residual network are learning the residual (R(x)). Hence, the name: Residual Block." }, { "code": null, "e": 4448, "s": 3563, "text": "It has also been observed that it is easier to learn residual of output and input, rather than only the input. As an added advantage, our network can now learn identity function by simply setting residual as zero. And if you truly understand backpropagation and how severe the problem of vanishing gradient becomes with increasing the number of layers, then you can clearly see that because of these skip connections, we can propagate larger gradients to initial layers, and these layers also could learn as fast as the final layers, giving us the ability to train deeper networks. The image below shows how to arrange the residual block and identity connections for the optimal gradient flow. It has been observed that pre-activations with batch normalizations generally give the best results (i.e., the right-most residual block in the image below gives the most promising results)." }, { "code": null, "e": 4971, "s": 4448, "text": "There are even more interpretations of residual blocks and ResNets, other than the ones already discussed above. While training ResNets, we either train the layers in residual blocks or skip the training for those layers using skip connections. So, different parts of networks will be trained at different rates for different training data points based on how the error flows backward in the network. This can be thought of as training an ensemble of different models on the dataset and getting the best possible accuracy." }, { "code": null, "e": 5596, "s": 4971, "text": "Skipping training in some residual block layers can be looked at from an optimistic point of view too. In general, we do not know the optimal number of layers (or residual blocks) required for a neural network which might depend on the complexity of the dataset. Instead of treating the number of layers as an important hyperparameter to tune, by adding skip connections to our network, we are allowing the network to skip training for the layers that are not useful and do not add value in overall accuracy. In a way, skip connections make our neural networks dynamic to tune the number of layers during training optimally." }, { "code": null, "e": 5664, "s": 5596, "text": "The image below shows multiple interpretations of a residual block." }, { "code": null, "e": 6242, "s": 5664, "text": "Let us go a little into the history of skip connections. The idea of skipping connections between the layers was first introduced in Highway Networks. Highway networks had skip connections with gates that controlled how much information is passed through them, and these gates can be trained to open selectively. This idea is also seen in the LSTM networks that control how much information flows from the past data points seen by the network. These gates work similarly to control of memory flow from the previously seen data points. The same idea is shown in the image below." }, { "code": null, "e": 6700, "s": 6242, "text": "Residual blocks are basically a special case of highway networks without any gates in their skip connections. Essentially, residual blocks allow memory (or information) to flow from initial to last layers. Despite the absence of gates in their skip connections, residual networks perform as well as any other highway network in practice. And before ending this article, below is an image of how the collection of all residual blocks completes into a ResNet." } ]
Batch Script - RD
This batch command removes directories, but the directories need to be empty before they can be removed. rd [directoryname] The following example shows the different variants of the rd command. @echo off Rem removes the directory called newdir rd C:\newdir Rem removes 2 directories rd Dir1 Dir2 Rem Removes directory with spaces rd "Application A" Rem Removes the directory Dir1 including all the files and subdirectories in it rd /s Dir1 Rem Removes the directory Dir1 including all the files and subdirectories in it but asks for a user confirmation first. rd /q /s Dir1 All actions are performed as per the remarks in the batch file. Print Add Notes Bookmark this page
[ { "code": null, "e": 2274, "s": 2169, "text": "This batch command removes directories, but the directories need to be empty before they can be removed." }, { "code": null, "e": 2294, "s": 2274, "text": "rd [directoryname]\n" }, { "code": null, "e": 2364, "s": 2294, "text": "The following example shows the different variants of the rd command." }, { "code": null, "e": 2747, "s": 2364, "text": "@echo off\nRem removes the directory called newdir\nrd C:\\newdir\n\nRem removes 2 directories\nrd Dir1 Dir2\n\nRem Removes directory with spaces\nrd \"Application A\"\n\nRem Removes the directory Dir1 including all the files and subdirectories in it rd /s Dir1\nRem Removes the directory Dir1 including all the files and subdirectories in it but\nasks for a user confirmation first.\nrd /q /s Dir1" }, { "code": null, "e": 2811, "s": 2747, "text": "All actions are performed as per the remarks in the batch file." }, { "code": null, "e": 2818, "s": 2811, "text": " Print" }, { "code": null, "e": 2829, "s": 2818, "text": " Add Notes" } ]
Jackson Annotations - @JsonCreator
@JsonCreator is used to fine tune the constructor or factory method used in deserialization. We'll be using @JsonProperty as well to achieve the same. In the example below, we are matching an json with different format to our class by defining the required property names. import java.io.IOException; import java.text.ParseException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]) throws ParseException{ String json = "{\"id\":1,\"theName\":\"Mark\"}"; ObjectMapper mapper = new ObjectMapper(); try { Student student = mapper .readerFor(Student.class) .readValue(json); System.out.println(student.rollNo +", " + student.name); } catch (IOException e) { e.printStackTrace(); } } } class Student { public String name; public int rollNo; @JsonCreator public Student(@JsonProperty("theName") String name, @JsonProperty("id") int rollNo){ this.name = name; this.rollNo = rollNo; } } 1, Mark Print Add Notes Bookmark this page
[ { "code": null, "e": 2748, "s": 2475, "text": "@JsonCreator is used to fine tune the constructor or factory method used in deserialization. We'll be using @JsonProperty as well to achieve the same. In the example below, we are matching an json with different format to our class by defining the required property names." }, { "code": null, "e": 3678, "s": 2748, "text": "import java.io.IOException; \nimport java.text.ParseException; \n\nimport com.fasterxml.jackson.annotation.JsonCreator; \nimport com.fasterxml.jackson.annotation.JsonProperty; \nimport com.fasterxml.jackson.databind.ObjectMapper; \n\npublic class JacksonTester {\n public static void main(String args[]) throws ParseException{ \n String json = \"{\\\"id\\\":1,\\\"theName\\\":\\\"Mark\\\"}\"; \n ObjectMapper mapper = new ObjectMapper(); \n try {\n Student student = mapper \n .readerFor(Student.class) \n .readValue(json); \n System.out.println(student.rollNo +\", \" + student.name); \n }\n catch (IOException e) { \n e.printStackTrace(); \n }\n }\n}\nclass Student {\n public String name; \n public int rollNo; \n\n @JsonCreator \n public Student(@JsonProperty(\"theName\") String name, @JsonProperty(\"id\") int rollNo){\n this.name = name; \n this.rollNo = rollNo; \n }\n}" }, { "code": null, "e": 3688, "s": 3678, "text": "1, Mark \n" }, { "code": null, "e": 3695, "s": 3688, "text": " Print" }, { "code": null, "e": 3706, "s": 3695, "text": " Add Notes" } ]
Python program for addition and subtraction of complex numbers - GeeksforGeeks
13 Dec, 2021 Given two complex numbers z1 and z2. The task is to add and subtract the given complex numbers.Addition of complex number: In Python, complex numbers can be added using + operator.Examples: Input: 2+3i, 4+5i Output: Addition is : 6+8i Input: 2+3i, 1+2i Output: Addition is : 3+5i Example : Python3 # Python program to add# two complex numbers # function that returns# a complex number after# addingdef addComplex( z1, z2): return z1 + z2 # Driver's codez1 = complex(2, 3)z2 = complex(1, 2)print( "Addition is : ", addComplex(z1, z2)) Output: Addition is : (3+5j) Subtraction of complex numbers: Complex numbers in Python can be subtracted using – operator.Examples: Input: 2+3i, 4+5i Output: Subtraction is : -2-2i Input: 2+3i, 1+2i Output: Subtraction is : 1+1i Example : Python3 # Python program to subtract# two complex numbers # function that returns# a complex number after# subtractingdef subComplex( z1, z2): return z1-z2 # driver programz1 = complex(2, 3)z2 = complex(1, 2)print( "Subtraction is : ", subComplex(z1, z2)) Output: Subtraction is : (1+1j) simmytarika5 sweetyty python-utility Technical Scripter 2019 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24819, "s": 24791, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25011, "s": 24819, "text": "Given two complex numbers z1 and z2. The task is to add and subtract the given complex numbers.Addition of complex number: In Python, complex numbers can be added using + operator.Examples: " }, { "code": null, "e": 25103, "s": 25011, "text": "Input: 2+3i, 4+5i\nOutput: Addition is : 6+8i\n\nInput: 2+3i, 1+2i\nOutput: Addition is : 3+5i" }, { "code": null, "e": 25114, "s": 25103, "text": " Example :" }, { "code": null, "e": 25122, "s": 25114, "text": "Python3" }, { "code": "# Python program to add# two complex numbers # function that returns# a complex number after# addingdef addComplex( z1, z2): return z1 + z2 # Driver's codez1 = complex(2, 3)z2 = complex(1, 2)print( \"Addition is : \", addComplex(z1, z2))", "e": 25362, "s": 25122, "text": null }, { "code": null, "e": 25371, "s": 25362, "text": "Output: " }, { "code": null, "e": 25393, "s": 25371, "text": "Addition is : (3+5j)" }, { "code": null, "e": 25498, "s": 25393, "text": "Subtraction of complex numbers: Complex numbers in Python can be subtracted using – operator.Examples: " }, { "code": null, "e": 25596, "s": 25498, "text": "Input: 2+3i, 4+5i\nOutput: Subtraction is : -2-2i\n\nInput: 2+3i, 1+2i\nOutput: Subtraction is : 1+1i" }, { "code": null, "e": 25607, "s": 25596, "text": "Example : " }, { "code": null, "e": 25615, "s": 25607, "text": "Python3" }, { "code": "# Python program to subtract# two complex numbers # function that returns# a complex number after# subtractingdef subComplex( z1, z2): return z1-z2 # driver programz1 = complex(2, 3)z2 = complex(1, 2)print( \"Subtraction is : \", subComplex(z1, z2))", "e": 25867, "s": 25615, "text": null }, { "code": null, "e": 25876, "s": 25867, "text": "Output: " }, { "code": null, "e": 25901, "s": 25876, "text": "Subtraction is : (1+1j)" }, { "code": null, "e": 25916, "s": 25903, "text": "simmytarika5" }, { "code": null, "e": 25925, "s": 25916, "text": "sweetyty" }, { "code": null, "e": 25940, "s": 25925, "text": "python-utility" }, { "code": null, "e": 25964, "s": 25940, "text": "Technical Scripter 2019" }, { "code": null, "e": 25971, "s": 25964, "text": "Python" }, { "code": null, "e": 25987, "s": 25971, "text": "Python Programs" }, { "code": null, "e": 26006, "s": 25987, "text": "Technical Scripter" }, { "code": null, "e": 26104, "s": 26006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26113, "s": 26104, "text": "Comments" }, { "code": null, "e": 26126, "s": 26113, "text": "Old Comments" }, { "code": null, "e": 26144, "s": 26126, "text": "Python Dictionary" }, { "code": null, "e": 26179, "s": 26144, "text": "Read a file line by line in Python" }, { "code": null, "e": 26201, "s": 26179, "text": "Enumerate() in Python" }, { "code": null, "e": 26233, "s": 26201, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26263, "s": 26233, "text": "Iterate over a list in Python" }, { "code": null, "e": 26306, "s": 26263, "text": "Python program to convert a list to string" }, { "code": null, "e": 26328, "s": 26306, "text": "Defaultdict in Python" }, { "code": null, "e": 26367, "s": 26328, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26413, "s": 26367, "text": "Python | Split string into list of characters" } ]
Difference between Abstract Class and Interface in Java
Following are the notable differences between interface and abstract class in Java. public class Tester { public static void main(String[] args) { Car car = new Car(); car.setFuel(); car.run(); Truck truck = new Truck(); truck.setFuel(); truck.run(); } } interface Vehicle { public void setFuel(); public void run(); } class Car implements Vehicle { public void setFuel() { System.out.println("Car: Tank is full."); } public void run() { System.out.println("Car: Running."); } } abstract class MotorVehicle { public void setFuel() { System.out.println("MotorVehicle: Tank is full."); } abstract public void run(); } class Truck extends MotorVehicle { public void run() { System.out.println("Truck: Running."); } } Car: Tank is full. Car: Running. MotorVehicle: Tank is full. Truck: Running.
[ { "code": null, "e": 1146, "s": 1062, "text": "Following are the notable differences between interface and abstract class in Java." }, { "code": null, "e": 1876, "s": 1146, "text": "public class Tester {\n public static void main(String[] args) {\n\n Car car = new Car();\n car.setFuel();\n car.run();\n Truck truck = new Truck();\n truck.setFuel();\n truck.run();\n }\n}\ninterface Vehicle {\n public void setFuel();\n public void run();\n}\nclass Car implements Vehicle {\n public void setFuel() {\n System.out.println(\"Car: Tank is full.\");\n }\n public void run() {\n System.out.println(\"Car: Running.\");\n }\n}\nabstract class MotorVehicle {\n public void setFuel() {\n System.out.println(\"MotorVehicle: Tank is full.\");\n }\n abstract public void run();\n}\nclass Truck extends MotorVehicle {\n public void run() {\n System.out.println(\"Truck: Running.\");\n }\n}" }, { "code": null, "e": 1953, "s": 1876, "text": "Car: Tank is full.\nCar: Running.\nMotorVehicle: Tank is full.\nTruck: Running." } ]
Python | Remove last element from each row in Matrix - GeeksforGeeks
30 Dec, 2020 Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + del + list slicingThe combination of above functionalities can be used to perform this task. In this, we run a loop for each row in matrix and remove the rear element using del. # Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using loop + del + list slicing # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]] # printing original list print("The original list : " + str(test_list)) # Remove last element from each row in Matrix# Using loop + del + list slicingfor ele in test_list: del ele[-1] # printing resultprint("Matrix after removal of rear element from rows : " + str(test_list)) The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]] Matrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]] Method #2 : Using list comprehension + list slicingThe combination of above functions can also be used to perform this task. In this, we just iterate for each row and delete the rear element using list slicing. # Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using list comprehension + list slicing # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]] # printing original list print("The original list : " + str(test_list)) # Remove last element from each row in Matrix# Using list comprehension + list slicingres = [ele[:-1] for ele in test_list] # printing resultprint("Matrix after removal of rear element from rows : " + str(res)) The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]] Matrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]] Python list-programs Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24099, "s": 24071, "text": "\n30 Dec, 2020" }, { "code": null, "e": 24335, "s": 24099, "text": "Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24538, "s": 24335, "text": "Method #1 : Using loop + del + list slicingThe combination of above functionalities can be used to perform this task. In this, we run a loop for each row in matrix and remove the rear element using del." }, { "code": "# Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using loop + del + list slicing # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]] # printing original list print(\"The original list : \" + str(test_list)) # Remove last element from each row in Matrix# Using loop + del + list slicingfor ele in test_list: del ele[-1] # printing resultprint(\"Matrix after removal of rear element from rows : \" + str(test_list))", "e": 25002, "s": 24538, "text": null }, { "code": null, "e": 25131, "s": 25002, "text": "The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]\nMatrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]]\n" }, { "code": null, "e": 25344, "s": 25133, "text": "Method #2 : Using list comprehension + list slicingThe combination of above functions can also be used to perform this task. In this, we just iterate for each row and delete the rear element using list slicing." }, { "code": "# Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using list comprehension + list slicing # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]] # printing original list print(\"The original list : \" + str(test_list)) # Remove last element from each row in Matrix# Using list comprehension + list slicingres = [ele[:-1] for ele in test_list] # printing resultprint(\"Matrix after removal of rear element from rows : \" + str(res))", "e": 25821, "s": 25344, "text": null }, { "code": null, "e": 25950, "s": 25821, "text": "The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]\nMatrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]]\n" }, { "code": null, "e": 25971, "s": 25950, "text": "Python list-programs" }, { "code": null, "e": 25993, "s": 25971, "text": "Python matrix-program" }, { "code": null, "e": 26000, "s": 25993, "text": "Python" }, { "code": null, "e": 26016, "s": 26000, "text": "Python Programs" }, { "code": null, "e": 26114, "s": 26016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26123, "s": 26114, "text": "Comments" }, { "code": null, "e": 26136, "s": 26123, "text": "Old Comments" }, { "code": null, "e": 26154, "s": 26136, "text": "Python Dictionary" }, { "code": null, "e": 26176, "s": 26154, "text": "Enumerate() in Python" }, { "code": null, "e": 26208, "s": 26176, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26250, "s": 26208, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26276, "s": 26250, "text": "Python String | replace()" }, { "code": null, "e": 26298, "s": 26276, "text": "Defaultdict in Python" }, { "code": null, "e": 26337, "s": 26298, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26383, "s": 26337, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26421, "s": 26383, "text": "Python | Convert a list to dictionary" } ]
Machine Learning Classification Project: Finding Donors | by Victor Roman | Towards Data Science
In this project, we will use a number of different supervised algorithms to precisely predict individuals’ income using data collected from the 1994 U.S. Census. We will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Our goal with this implementation is to build a model that accurately predicts whether an individual makes more than $50,000. This sort of task can arise in a non-profit setting, where organizations survive on donations. Understanding an individual’s income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with. As from our previous research we have found out that the individuals who are most likely to donate money to a charity are the ones that make more than $50,000. The dataset for this project originates from the UCI Machine Learning Repository. The datset was donated by Ron Kohavi and Barry Becker, after being published in the article “Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid”. You can find the article by Ron Kohavi online. The data we investigate here consists of small changes to the original dataset, such as removing the 'fnlwgt' feature and records with missing or ill-formatted entries. The modified census dataset consists of approximately 32,000 data points, with each datapoint having 13 features. This dataset is a modified version of the dataset published in the paper “Scaling Up the Accuracy of Naive-Bayes Classifiers: a Decision-Tree Hybrid”, by Ron Kohavi. You may find this paper online, with the original dataset hosted on UCI. Features age: Age workclass: Working Class (Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked) education_level: Level of Education (Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool) education-num: Number of educational years completed marital-status: Marital status (Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse) occupation: Work Occupation (Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces) relationship: Relationship Status (Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried) race: Race (White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black) sex: Sex (Female, Male) capital-gain: Monetary Capital Gains capital-loss: Monetary Capital Losses hours-per-week: Average Hours Per Week Worked native-country: Native Country (United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands) Target Variable income: Income Class (<=50K, >50K) We will first load the Python libraries that we are going to use, as well as the census data. The last column will be our target variable, ‘income’, and the rest will be the features. # Import libraries necessary for this projectimport numpy as npimport pandas as pdfrom time import timefrom IPython.display import display # Import supplementary visualization code visuals.pyimport visuals as vs# Pretty display for notebooks%matplotlib inline# Load the Census datasetdata = pd.read_csv("census.csv")# Success - Display the first recorddisplay(data.head(n=1)) An initial exploration of the dataset will show us how many individuals fit in each group and the proportion of them that earn more than $50,000. # Total number of recordsn_records = data.shape[0]# Number of records where individual's income is more than $50,000n_greater_50k = data[data['income'] == '>50K'].shape[0]# Number of records where individual's income is at most $50,000n_at_most_50k = data[data['income'] == '<=50K'].shape[0]# Percentage of individuals whose income is more than $50,000greater_percent = (n_greater_50k / n_records) * 100# Print the resultsprint("Total number of records: {}".format(n_records))print("Individuals making more than $50,000: {}".format(n_greater_50k))print("Individuals making at most $50,000: {}".format(n_at_most_50k))print("Percentage of individuals making more than $50,000: {}%".format(greater_percent)) Data must be preprocessed in order to be used in Machine Learning algorithms. This preprocessing phase includes the cleaning, formatting and reestructuring of the data. For this dataset there aren’t empty entries nor invalid ones, but, there are some features that must be adjusted. This task will dramatically improve the results and the predictive power of our model. Transforming Skewed Continuous Fetures Skewed distributions on the feature’s values can make an algorithm to underperfom if the range is not normalized. In our dataset, there are two features with this distribution: ‘capital-gain’ ‘capital-loss’ # Split the data into features and target labelincome_raw = data['income']features_raw = data.drop('income', axis = 1)# Visualize skewed continuous features of original datavs.distribution(data) For this type of disttributions, is very typical to apply logarithmic transformationon the data, so the outliers do not affect negatively the machine learning model’s performance. However, we should carefully treat the 0 values, as the log(0) is undefined, so we will translate these values to a small amount above 0 to apply the logarithm succesfully. # Log-transform the skewed featuresskewed = ['capital-gain', 'capital-loss']features_log_transformed = pd.DataFrame(data = features_raw)features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))# Visualize the new log distributionsvs.distribution(features_log_transformed, transformed = True) Normalizing Numerical Features It is recommended to perform some type of scaling on numerical features. This scaling will not change the shape of the feature’s distribution but it ensures the equal treatment of each feature when supervised models are applied. # Import sklearn.preprocessing.StandardScalerfrom sklearn.preprocessing import MinMaxScaler# Initialize a scaler, then apply it to the featuresscaler = MinMaxScaler() # default=(0, 1)numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])# Show an example of a record with scaling applieddisplay(features_log_minmax_transform.head(n = 5)) Preprocessing Categorial Features If we take a look at the previous table, we can see that there are some features like ‘occupation’ or ‘race’ that are not numerical, they are categorical. Machine learning algorithms expect to work with numerical values, so these categorical features should be transformed. One of the most popular categorical transformations is called ‘one-hot encoding’. In one-hot encoding, there is created a ‘dummy’ variable for each possible category of the categorical feature. For a better understanding, take a look at the following table: In addition, we should transform our target variable ‘income’. It can only take to possible values, “<=50K” and “>50K”, so we will avoid one-hot encoding and codify the categories as 0 and 1, respectively. features_log_minmax_transform.head(1) # One-hot encode the 'features_log_minmax_transform' data features_final = pd.get_dummies(features_log_minmax_transform)# Encode the 'income_raw' data to numerical valuesincome = income_raw.map({'<=50K':0,'>50K':1})# Print the number of features after one-hot encodingencoded = list(features_final.columns)print("{} total features after one-hot encoding.".format(len(encoded)))# See the encoded feature namesprint (encoded) Shuffle and Split Data When all categorical variables are transformed, and all numerical features normalized, we need to split our data into training and test sets. We’ll use 80% of the data to training and 20% for testing, # Import train_test_split from sklearn.model_selection import train_test_split # Split the 'features' and 'income' data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features_final, income, test_size = 0.2, random_state = 0) # Show the results of the split print("Training set has {} samples.".format(X_train.shape[0])) print("Testing set has {} samples.".format(X_test.shape[0])) In this section, we will study four different algorithms, and determine the best at modeling and predicting our data. One of these algorithms will be a naive predictor which will serve as a baseline of performance and, the other three will be supervised learners. Metrics and The Naive Predictor The objective of the project is to correctly identify what individuals make more than 50k$ per year, as they are the group most likely to donate money to charity. Therefore we should choose wisely our evaluation metric. Note: Evaluation Metrics reminder When making predictions on events we can get 4 type of results: True Positives, True Negatives, False Positives and False Negatives. All of these are represented in the following classification matrix: Accuracy measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points). Precision tells us what proportion of events we classified as a certain class, actually were that class. It is a ratio of true positives to all positives. Recall (sensitivity) tells us what proportion of events that actually were the of a certain class were classified by us as that class. It is a ratio of true positives to all the positives. For classification problems that are skewed in their classification distributions like in our case, accuracy by itself is not an appropiate metric. Instead, precision and recall are much more representative. These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios). In addition, since we are searching individuals willing to donate, the model’s ability to precisely predict those that make more than $50,000 is more important than the model’s ability to recall those individuals. We can use F-beta score as a metric that considers both precision and recall. Concretely, for β = 0.5, it is given more importance on precision. If we take a look at the distribution of classes of the ‘income’ variable, it is evident that there are a lot more people that make at most $50K per year than those who make more. So, we could make the naive predicition of taking a random individual, and predicting that he/she will not make more than $50K per year. It is called naive because we haven’t considered any relevant information to substantiate the claim. This naive prediction will serve us as a benchmark to determine if our model is performing well or not. It is important to notice that it is pointless to use this type of prediction by itself as all individuals would be classified as not donors. Naive Predictor Performance We’ll run the following code to determine our naive predictor performance: # Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data encoded to numerical values done in the data preprocessing step.TP = np.sum(income) # Specific to the naive caseFP = income.count() - TP# No predicted negatives in the naive caseTN = 0 FN = 0 # Calculate accuracy, precision and recallaccuracy = TP / (TP + FP + TN + FN)recall = TP / (TP + FN)precision = TP / (TP + FP)# Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.beta = 0.5fscore = (1 + beta**2) * ((precision * recall) / ((beta**2) * precision + recall))# Print the results print("Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore)) Considering the shape of our data: 45222 datapoints 103 Features The number of datapoints is not very large but there is a significat amount of features and not all supervised algorithms are suitable to handle quantity appropiately. Some of the available Classification algorithms in scikit-learn: Gaussian Naive Bayes (GaussianNB) Decision Trees Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting) K-Nearest Neighbors (KNeighbors) Stochastic Gradient Descent Classifier (SGDC) Support Vector Machines (SVM) Logistic Regression Considering their characteristics and our dataset, we’ll choose the following three: a) Gaussian Naive Bayes The strenghts of the model are: It is simple and fast classifier that provides good results with little tunning of the model’s hyperparameters. In addition, it does not require a large amount of data to be propperly trained. The weaknesses of the model are: It has a strong feature independece assumptions. If we do not have ocurrences of a class label and a certain attribute value together (e.g. class = ‘nice’, shape = ‘sphere’) then the frequency-based probability estimate will be zero, so given the conditional independence assumption, when all the probabilities are multiplied we will get zero, which will affect the posterior probabilty estimate. One possible real world application where this model can be applied is for text learning. It is a good candidate because it is an efficient model and can deal with many features (the data set contains 98 features). b) Random Forests The strenghts of the model are: It works well with binary features, as it is an ensembling of decision trees. It does not expect linear features. It works well with high dimensional spaces and large number of training examples. The main weakness is that it may overfit when dealing wih noisy data. One possible real world application where this model can be applied is for predicting stock market prices. It is a good candidate because it is often a quite accurate classificator and works well with binary features and high dimensional datasets. c) Support Vector Machines Classifier The strenghts of the model are: It works well with no linearly separable data and high dimensional spaces. The main weakness is that it may be quite inefficient to train, so it is no suitable for “industrial scale” applications. One possible real world application where this model can be applied is for classifying people with and without common diseases. It is a good candidate because it is often a quite accurate classificator and works well with binary features and high dimensional datasets. Creating a Training and Predicting Pipeline To properly evaluate the performance of each model, we will create a training and predicting pipeline that will allow us to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. # Import two metrics from sklearn - fbeta_score and accuracy_scoredef train_predict(learner, sample_size, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples (number) to be drawn from training set - X_train: features training set - y_train: income training set - X_test: features testing set - y_test: income testing set ''' results = {} # Fit the learner to the training data start = time() # Get start time learner = learner.fit(X_train[:sample_size], y_train[:sample_size]) end = time() # Get end time # Calculate the training time results['train_time'] = end - start # Get the predictions on the test set start = time() # Get start time predictions_test = learner.predict(X_test) predictions_train = learner.predict(X_train[:300]) end = time() # Get end time # Calculate the total prediction time results['pred_time'] = end -start # Compute accuracy on the first 300 training samples results['acc_train'] = accuracy_score(y_train[:300], predictions_train) # Compute accuracy on test set using accuracy_score() results['acc_test'] = accuracy_score(y_test, predictions_test) # Compute F-score on the the first 300 training samples results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5) # Compute F-score on the test set which is y_test results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5) # Success print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size)) # Return the results return results # Import the three supervised learning models from sklearnfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.svm import SVC# Initialize the three modelsrandom_state = 42clf_A = RandomForestClassifier(random_state=random_state)clf_B = GaussianNB()clf_C = SVC(random_state=random_state)# Calculate the number of samples for 1%, 10%, and 100% of the training datasamples_100 = len(y_train)samples_10 = int(len(y_train)/10)samples_1 = int(len(y_train)/100)# Collect results on the learnersresults = {}for clf in [clf_A, clf_B, clf_C]: clf_name = clf.__class__.__name__ results[clf_name] = {} for i, samples in enumerate([samples_1, samples_10, samples_100]): results[clf_name][i] = \ train_predict(clf, samples, X_train, y_train, X_test, y_test)# Run metrics visualization for the three supervised learning models chosenvs.evaluate(results, accuracy, fscore) Finally, in this section we will choose the best model to use on our data, and then, perform a grid search optimization for ther model over the entire training set (X_train and y_train) by tunning parameters to improve the model’s F-score. Choosing the Best Model Based on the results of the evaluation, the most appropiate model to identify potential donors is the Random Forest Classifier as it yields the same F-score of the Support Vector Classifier but in much less time. This is coherent with our knowledge of the algorithm as it is a very good choice when dealing with high-dimensional datasets, in other words, datasets with a large number of features. So among the evaluated models, this is the more efficient one and best the suited to work with our dataset. Describing Random Forest in Layman’s Terms To understand Random Forests Classificators we need first to introduce the concept of Decision Trees. A Decision Tree is a flowchart-like structure, in which each internal node represents a test on an attribute of the dataset, each brand represents the outcome of the test and each leaf represents a class label. So the algorithm will make the tests on the data, finding out which are the most relevant features of the dataset to predict a certain outcome, and separating accordingly the dataset. The following is an example of a decision tree to decide wheter or not you lend your car to someone: A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy of the model, and control overfitting by preventing it to become too complex and unable to generalize on unseen data. It randomly selects a number of features and trains each decision tree classifier in every sub-set of the features. Then, it each decision tree to make predictions by making them vote for the correct label. Random Forests classifiers are quite popular in classification problems due to its simplicity to use, efficiency and its good predicting accuracy. Model Tunning We will now fine tune the chosen model, using GridSearchCV. # Import the necessary librariesfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorer# Initialize the classifierclf = RandomForestClassifier(random_state = 42)# Create the parameters list parameters = { 'max_depth': [10,20,30,40], 'max_features': [2, 3], 'min_samples_leaf': [3, 4, 5], 'min_samples_split': [8, 10, 12], 'n_estimators': [50,100,150]}# Make an fbeta_score scoring object using make_scorer()scorer = make_scorer(fbeta_score, beta=0.5)# Perform grid search on the classifier grid_obj = GridSearchCV(estimator=clf, param_grid=parameters, scoring=scorer)# Fit the grid search object to the training data grid_fit = grid_obj.fit(X_train, y_train)# Get the estimatorbest_clf = grid_fit.best_estimator_# Make predictions using the unoptimized and modelpredictions = (clf.fit(X_train, y_train)).predict(X_test)best_predictions = best_clf.predict(X_test)# Report the before-and-afterscoresprint("Unoptimized model\n------")print("Accuracy score on testing data {:.4f}".format(accuracy_score(y_test, predictions)))print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = 0.5)))print("\nOptimized Model\n------")print("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))print("Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5))) # Show the best classifier hyperparametersbest_clf Observations The optimized model’s accuracy and F-score on testing data are: 84.8% and 71.38% respectively. These scores are slightly better than the ones of the unoptimized model but the computing time is far larger. The naive predictor benchmarks for the accuracy and F-score are 24.78% and 29.27% respectively, which are much worse than the ones obtained with the trained model. Extra: Feature Importance An important task when performing supervised learning on a dataset like his one is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than $50,000. Intuitively, of the 13 features available on the original datasetwe can infer that the most important ones for predicting the income are: 1) age 2) education 3) native-country 4) occupation 5) hours per week The rank’s order logic is the following: It is likely that a person’s income would increase over the years and older people tend to earn more money than younger ones. In additon, people who have higher education tend to get higher paid jobs and this is a factor that is also heavily related with the native country as, usually, people that are native of economically stronger countries tend to have access to higher education. Occupation is an important feature to take into consideration as yearly income vary a lot depending on the industry and sector. Finally, hours per week as normally, people who work more hours tend to earn more. We will now chek the accuracy of our logic by passing our data through a model that hast the feature_importance_ method: # Import Ada Boost Classifierfrom sklearn.ensemble import AdaBoostClassifier# Train the supervised model on the training model = AdaBoostClassifier().fit(X_train, y_train)# Extract the feature importances using .feature_importances_ importances = model.feature_importances_# Plotvs.feature_plot(importances, X_train, y_train) The intution followed in the previous section was partially right as the AdaBoost tests shows that feautures like age, hours per week and education are quite relevant to predict the income. However, we didn’t indentified capital-loss and capital-gain. Feature Selection Now it is reasonable to ask the following: How does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of all features present in the data. This hints that we can attempt to reduce the feature space and simplify the information required for the model to learn. # Import functionality for cloning a modelfrom sklearn.base import clone# Reduce the feature spaceX_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]# Train on the "best" model found from grid search earlierclf = (clone(best_clf)).fit(X_train_reduced, y_train)# Make new predictionsreduced_predictions = clf.predict(X_test_reduced)# Report scores from the final model using both versions of dataprint("Final Model trained on full data\n------")print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))print("\nFinal Model trained on reduced data\n------")print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, reduced_predictions)))print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, reduced_predictions, beta = 0.5))) Observations of the Effects of Feature Selection Both accuracy and f-score are lower on the reduced data than on the original dataset. Specially f-score 71.38% vs 67.57% Considering the metrics obtained in the evaluations made on the default model, the optimized model and the reduced dataset, the best option would be to use the default model version with the complete dataset as it yields a good combination of accuracy and f-score in a good training time. Throughout this article we made a machine learning classification project from end-to-end and we learned and obtained several insights about classification models and the keys to develop one with a good performance. This was the third of the machine learning projects that have been explained inthis series. If you liked it, check out the previous one: Regression Project Naive Bayes Project Stay tuned for the next article! Which will be an introduction to the theory and concepts regarding to Unsupervised Learning. If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here. If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
[ { "code": null, "e": 334, "s": 172, "text": "In this project, we will use a number of different supervised algorithms to precisely predict individuals’ income using data collected from the 1994 U.S. Census." }, { "code": null, "e": 594, "s": 334, "text": "We will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Our goal with this implementation is to build a model that accurately predicts whether an individual makes more than $50,000." }, { "code": null, "e": 1017, "s": 594, "text": "This sort of task can arise in a non-profit setting, where organizations survive on donations. Understanding an individual’s income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with. As from our previous research we have found out that the individuals who are most likely to donate money to a charity are the ones that make more than $50,000." }, { "code": null, "e": 1485, "s": 1017, "text": "The dataset for this project originates from the UCI Machine Learning Repository. The datset was donated by Ron Kohavi and Barry Becker, after being published in the article “Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid”. You can find the article by Ron Kohavi online. The data we investigate here consists of small changes to the original dataset, such as removing the 'fnlwgt' feature and records with missing or ill-formatted entries." }, { "code": null, "e": 1838, "s": 1485, "text": "The modified census dataset consists of approximately 32,000 data points, with each datapoint having 13 features. This dataset is a modified version of the dataset published in the paper “Scaling Up the Accuracy of Naive-Bayes Classifiers: a Decision-Tree Hybrid”, by Ron Kohavi. You may find this paper online, with the original dataset hosted on UCI." }, { "code": null, "e": 1847, "s": 1838, "text": "Features" }, { "code": null, "e": 1856, "s": 1847, "text": "age: Age" }, { "code": null, "e": 1985, "s": 1856, "text": "workclass: Working Class (Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked)" }, { "code": null, "e": 2173, "s": 1985, "text": "education_level: Level of Education (Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool)" }, { "code": null, "e": 2226, "s": 2173, "text": "education-num: Number of educational years completed" }, { "code": null, "e": 2365, "s": 2226, "text": "marital-status: Marital status (Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse)" }, { "code": null, "e": 2612, "s": 2365, "text": "occupation: Work Occupation (Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces)" }, { "code": null, "e": 2715, "s": 2612, "text": "relationship: Relationship Status (Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried)" }, { "code": null, "e": 2788, "s": 2715, "text": "race: Race (White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black)" }, { "code": null, "e": 2812, "s": 2788, "text": "sex: Sex (Female, Male)" }, { "code": null, "e": 2849, "s": 2812, "text": "capital-gain: Monetary Capital Gains" }, { "code": null, "e": 2887, "s": 2849, "text": "capital-loss: Monetary Capital Losses" }, { "code": null, "e": 2933, "s": 2887, "text": "hours-per-week: Average Hours Per Week Worked" }, { "code": null, "e": 3381, "s": 2933, "text": "native-country: Native Country (United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands)" }, { "code": null, "e": 3397, "s": 3381, "text": "Target Variable" }, { "code": null, "e": 3432, "s": 3397, "text": "income: Income Class (<=50K, >50K)" }, { "code": null, "e": 3616, "s": 3432, "text": "We will first load the Python libraries that we are going to use, as well as the census data. The last column will be our target variable, ‘income’, and the rest will be the features." }, { "code": null, "e": 3992, "s": 3616, "text": "# Import libraries necessary for this projectimport numpy as npimport pandas as pdfrom time import timefrom IPython.display import display # Import supplementary visualization code visuals.pyimport visuals as vs# Pretty display for notebooks%matplotlib inline# Load the Census datasetdata = pd.read_csv(\"census.csv\")# Success - Display the first recorddisplay(data.head(n=1))" }, { "code": null, "e": 4138, "s": 3992, "text": "An initial exploration of the dataset will show us how many individuals fit in each group and the proportion of them that earn more than $50,000." }, { "code": null, "e": 4843, "s": 4138, "text": "# Total number of recordsn_records = data.shape[0]# Number of records where individual's income is more than $50,000n_greater_50k = data[data['income'] == '>50K'].shape[0]# Number of records where individual's income is at most $50,000n_at_most_50k = data[data['income'] == '<=50K'].shape[0]# Percentage of individuals whose income is more than $50,000greater_percent = (n_greater_50k / n_records) * 100# Print the resultsprint(\"Total number of records: {}\".format(n_records))print(\"Individuals making more than $50,000: {}\".format(n_greater_50k))print(\"Individuals making at most $50,000: {}\".format(n_at_most_50k))print(\"Percentage of individuals making more than $50,000: {}%\".format(greater_percent))" }, { "code": null, "e": 5012, "s": 4843, "text": "Data must be preprocessed in order to be used in Machine Learning algorithms. This preprocessing phase includes the cleaning, formatting and reestructuring of the data." }, { "code": null, "e": 5213, "s": 5012, "text": "For this dataset there aren’t empty entries nor invalid ones, but, there are some features that must be adjusted. This task will dramatically improve the results and the predictive power of our model." }, { "code": null, "e": 5252, "s": 5213, "text": "Transforming Skewed Continuous Fetures" }, { "code": null, "e": 5366, "s": 5252, "text": "Skewed distributions on the feature’s values can make an algorithm to underperfom if the range is not normalized." }, { "code": null, "e": 5429, "s": 5366, "text": "In our dataset, there are two features with this distribution:" }, { "code": null, "e": 5444, "s": 5429, "text": "‘capital-gain’" }, { "code": null, "e": 5459, "s": 5444, "text": "‘capital-loss’" }, { "code": null, "e": 5654, "s": 5459, "text": "# Split the data into features and target labelincome_raw = data['income']features_raw = data.drop('income', axis = 1)# Visualize skewed continuous features of original datavs.distribution(data)" }, { "code": null, "e": 5834, "s": 5654, "text": "For this type of disttributions, is very typical to apply logarithmic transformationon the data, so the outliers do not affect negatively the machine learning model’s performance." }, { "code": null, "e": 6007, "s": 5834, "text": "However, we should carefully treat the 0 values, as the log(0) is undefined, so we will translate these values to a small amount above 0 to apply the logarithm succesfully." }, { "code": null, "e": 6328, "s": 6007, "text": "# Log-transform the skewed featuresskewed = ['capital-gain', 'capital-loss']features_log_transformed = pd.DataFrame(data = features_raw)features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))# Visualize the new log distributionsvs.distribution(features_log_transformed, transformed = True)" }, { "code": null, "e": 6359, "s": 6328, "text": "Normalizing Numerical Features" }, { "code": null, "e": 6588, "s": 6359, "text": "It is recommended to perform some type of scaling on numerical features. This scaling will not change the shape of the feature’s distribution but it ensures the equal treatment of each feature when supervised models are applied." }, { "code": null, "e": 7135, "s": 6588, "text": "# Import sklearn.preprocessing.StandardScalerfrom sklearn.preprocessing import MinMaxScaler# Initialize a scaler, then apply it to the featuresscaler = MinMaxScaler() # default=(0, 1)numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])# Show an example of a record with scaling applieddisplay(features_log_minmax_transform.head(n = 5))" }, { "code": null, "e": 7169, "s": 7135, "text": "Preprocessing Categorial Features" }, { "code": null, "e": 7443, "s": 7169, "text": "If we take a look at the previous table, we can see that there are some features like ‘occupation’ or ‘race’ that are not numerical, they are categorical. Machine learning algorithms expect to work with numerical values, so these categorical features should be transformed." }, { "code": null, "e": 7637, "s": 7443, "text": "One of the most popular categorical transformations is called ‘one-hot encoding’. In one-hot encoding, there is created a ‘dummy’ variable for each possible category of the categorical feature." }, { "code": null, "e": 7701, "s": 7637, "text": "For a better understanding, take a look at the following table:" }, { "code": null, "e": 7907, "s": 7701, "text": "In addition, we should transform our target variable ‘income’. It can only take to possible values, “<=50K” and “>50K”, so we will avoid one-hot encoding and codify the categories as 0 and 1, respectively." }, { "code": null, "e": 7945, "s": 7907, "text": "features_log_minmax_transform.head(1)" }, { "code": null, "e": 8369, "s": 7945, "text": "# One-hot encode the 'features_log_minmax_transform' data features_final = pd.get_dummies(features_log_minmax_transform)# Encode the 'income_raw' data to numerical valuesincome = income_raw.map({'<=50K':0,'>50K':1})# Print the number of features after one-hot encodingencoded = list(features_final.columns)print(\"{} total features after one-hot encoding.\".format(len(encoded)))# See the encoded feature namesprint (encoded)" }, { "code": null, "e": 8392, "s": 8369, "text": "Shuffle and Split Data" }, { "code": null, "e": 8593, "s": 8392, "text": "When all categorical variables are transformed, and all numerical features normalized, we need to split our data into training and test sets. We’ll use 80% of the data to training and 20% for testing," }, { "code": null, "e": 9172, "s": 8593, "text": "# Import train_test_split from sklearn.model_selection import train_test_split # Split the 'features' and 'income' data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features_final, income, test_size = 0.2, random_state = 0) # Show the results of the split print(\"Training set has {} samples.\".format(X_train.shape[0])) print(\"Testing set has {} samples.\".format(X_test.shape[0]))" }, { "code": null, "e": 9436, "s": 9172, "text": "In this section, we will study four different algorithms, and determine the best at modeling and predicting our data. One of these algorithms will be a naive predictor which will serve as a baseline of performance and, the other three will be supervised learners." }, { "code": null, "e": 9468, "s": 9436, "text": "Metrics and The Naive Predictor" }, { "code": null, "e": 9688, "s": 9468, "text": "The objective of the project is to correctly identify what individuals make more than 50k$ per year, as they are the group most likely to donate money to charity. Therefore we should choose wisely our evaluation metric." }, { "code": null, "e": 9722, "s": 9688, "text": "Note: Evaluation Metrics reminder" }, { "code": null, "e": 9924, "s": 9722, "text": "When making predictions on events we can get 4 type of results: True Positives, True Negatives, False Positives and False Negatives. All of these are represented in the following classification matrix:" }, { "code": null, "e": 10118, "s": 9924, "text": "Accuracy measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points)." }, { "code": null, "e": 10273, "s": 10118, "text": "Precision tells us what proportion of events we classified as a certain class, actually were that class. It is a ratio of true positives to all positives." }, { "code": null, "e": 10462, "s": 10273, "text": "Recall (sensitivity) tells us what proportion of events that actually were the of a certain class were classified by us as that class. It is a ratio of true positives to all the positives." }, { "code": null, "e": 10670, "s": 10462, "text": "For classification problems that are skewed in their classification distributions like in our case, accuracy by itself is not an appropiate metric. Instead, precision and recall are much more representative." }, { "code": null, "e": 10934, "s": 10670, "text": "These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios)." }, { "code": null, "e": 11226, "s": 10934, "text": "In addition, since we are searching individuals willing to donate, the model’s ability to precisely predict those that make more than $50,000 is more important than the model’s ability to recall those individuals. We can use F-beta score as a metric that considers both precision and recall." }, { "code": null, "e": 11293, "s": 11226, "text": "Concretely, for β = 0.5, it is given more importance on precision." }, { "code": null, "e": 11711, "s": 11293, "text": "If we take a look at the distribution of classes of the ‘income’ variable, it is evident that there are a lot more people that make at most $50K per year than those who make more. So, we could make the naive predicition of taking a random individual, and predicting that he/she will not make more than $50K per year. It is called naive because we haven’t considered any relevant information to substantiate the claim." }, { "code": null, "e": 11957, "s": 11711, "text": "This naive prediction will serve us as a benchmark to determine if our model is performing well or not. It is important to notice that it is pointless to use this type of prediction by itself as all individuals would be classified as not donors." }, { "code": null, "e": 11985, "s": 11957, "text": "Naive Predictor Performance" }, { "code": null, "e": 12060, "s": 11985, "text": "We’ll run the following code to determine our naive predictor performance:" }, { "code": null, "e": 12777, "s": 12060, "text": "# Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data encoded to numerical values done in the data preprocessing step.TP = np.sum(income) # Specific to the naive caseFP = income.count() - TP# No predicted negatives in the naive caseTN = 0 FN = 0 # Calculate accuracy, precision and recallaccuracy = TP / (TP + FP + TN + FN)recall = TP / (TP + FN)precision = TP / (TP + FP)# Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.beta = 0.5fscore = (1 + beta**2) * ((precision * recall) / ((beta**2) * precision + recall))# Print the results print(\"Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]\".format(accuracy, fscore))" }, { "code": null, "e": 12812, "s": 12777, "text": "Considering the shape of our data:" }, { "code": null, "e": 12829, "s": 12812, "text": "45222 datapoints" }, { "code": null, "e": 12842, "s": 12829, "text": "103 Features" }, { "code": null, "e": 13010, "s": 12842, "text": "The number of datapoints is not very large but there is a significat amount of features and not all supervised algorithms are suitable to handle quantity appropiately." }, { "code": null, "e": 13075, "s": 13010, "text": "Some of the available Classification algorithms in scikit-learn:" }, { "code": null, "e": 13109, "s": 13075, "text": "Gaussian Naive Bayes (GaussianNB)" }, { "code": null, "e": 13124, "s": 13109, "text": "Decision Trees" }, { "code": null, "e": 13195, "s": 13124, "text": "Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)" }, { "code": null, "e": 13228, "s": 13195, "text": "K-Nearest Neighbors (KNeighbors)" }, { "code": null, "e": 13274, "s": 13228, "text": "Stochastic Gradient Descent Classifier (SGDC)" }, { "code": null, "e": 13304, "s": 13274, "text": "Support Vector Machines (SVM)" }, { "code": null, "e": 13324, "s": 13304, "text": "Logistic Regression" }, { "code": null, "e": 13409, "s": 13324, "text": "Considering their characteristics and our dataset, we’ll choose the following three:" }, { "code": null, "e": 13433, "s": 13409, "text": "a) Gaussian Naive Bayes" }, { "code": null, "e": 13658, "s": 13433, "text": "The strenghts of the model are: It is simple and fast classifier that provides good results with little tunning of the model’s hyperparameters. In addition, it does not require a large amount of data to be propperly trained." }, { "code": null, "e": 14088, "s": 13658, "text": "The weaknesses of the model are: It has a strong feature independece assumptions. If we do not have ocurrences of a class label and a certain attribute value together (e.g. class = ‘nice’, shape = ‘sphere’) then the frequency-based probability estimate will be zero, so given the conditional independence assumption, when all the probabilities are multiplied we will get zero, which will affect the posterior probabilty estimate." }, { "code": null, "e": 14178, "s": 14088, "text": "One possible real world application where this model can be applied is for text learning." }, { "code": null, "e": 14303, "s": 14178, "text": "It is a good candidate because it is an efficient model and can deal with many features (the data set contains 98 features)." }, { "code": null, "e": 14321, "s": 14303, "text": "b) Random Forests" }, { "code": null, "e": 14549, "s": 14321, "text": "The strenghts of the model are: It works well with binary features, as it is an ensembling of decision trees. It does not expect linear features. It works well with high dimensional spaces and large number of training examples." }, { "code": null, "e": 14619, "s": 14549, "text": "The main weakness is that it may overfit when dealing wih noisy data." }, { "code": null, "e": 14726, "s": 14619, "text": "One possible real world application where this model can be applied is for predicting stock market prices." }, { "code": null, "e": 14867, "s": 14726, "text": "It is a good candidate because it is often a quite accurate classificator and works well with binary features and high dimensional datasets." }, { "code": null, "e": 14905, "s": 14867, "text": "c) Support Vector Machines Classifier" }, { "code": null, "e": 15012, "s": 14905, "text": "The strenghts of the model are: It works well with no linearly separable data and high dimensional spaces." }, { "code": null, "e": 15134, "s": 15012, "text": "The main weakness is that it may be quite inefficient to train, so it is no suitable for “industrial scale” applications." }, { "code": null, "e": 15262, "s": 15134, "text": "One possible real world application where this model can be applied is for classifying people with and without common diseases." }, { "code": null, "e": 15403, "s": 15262, "text": "It is a good candidate because it is often a quite accurate classificator and works well with binary features and high dimensional datasets." }, { "code": null, "e": 15447, "s": 15403, "text": "Creating a Training and Predicting Pipeline" }, { "code": null, "e": 15690, "s": 15447, "text": "To properly evaluate the performance of each model, we will create a training and predicting pipeline that will allow us to quickly and effectively train models using various sizes of training data and perform predictions on the testing data." }, { "code": null, "e": 17440, "s": 15690, "text": "# Import two metrics from sklearn - fbeta_score and accuracy_scoredef train_predict(learner, sample_size, X_train, y_train, X_test, y_test): ''' inputs: - learner: the learning algorithm to be trained and predicted on - sample_size: the size of samples (number) to be drawn from training set - X_train: features training set - y_train: income training set - X_test: features testing set - y_test: income testing set ''' results = {} # Fit the learner to the training data start = time() # Get start time learner = learner.fit(X_train[:sample_size], y_train[:sample_size]) end = time() # Get end time # Calculate the training time results['train_time'] = end - start # Get the predictions on the test set start = time() # Get start time predictions_test = learner.predict(X_test) predictions_train = learner.predict(X_train[:300]) end = time() # Get end time # Calculate the total prediction time results['pred_time'] = end -start # Compute accuracy on the first 300 training samples results['acc_train'] = accuracy_score(y_train[:300], predictions_train) # Compute accuracy on test set using accuracy_score() results['acc_test'] = accuracy_score(y_test, predictions_test) # Compute F-score on the the first 300 training samples results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=0.5) # Compute F-score on the test set which is y_test results['f_test'] = fbeta_score(y_test, predictions_test, beta=0.5) # Success print(\"{} trained on {} samples.\".format(learner.__class__.__name__, sample_size)) # Return the results return results" }, { "code": null, "e": 18375, "s": 17440, "text": "# Import the three supervised learning models from sklearnfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.svm import SVC# Initialize the three modelsrandom_state = 42clf_A = RandomForestClassifier(random_state=random_state)clf_B = GaussianNB()clf_C = SVC(random_state=random_state)# Calculate the number of samples for 1%, 10%, and 100% of the training datasamples_100 = len(y_train)samples_10 = int(len(y_train)/10)samples_1 = int(len(y_train)/100)# Collect results on the learnersresults = {}for clf in [clf_A, clf_B, clf_C]: clf_name = clf.__class__.__name__ results[clf_name] = {} for i, samples in enumerate([samples_1, samples_10, samples_100]): results[clf_name][i] = \\ train_predict(clf, samples, X_train, y_train, X_test, y_test)# Run metrics visualization for the three supervised learning models chosenvs.evaluate(results, accuracy, fscore)" }, { "code": null, "e": 18615, "s": 18375, "text": "Finally, in this section we will choose the best model to use on our data, and then, perform a grid search optimization for ther model over the entire training set (X_train and y_train) by tunning parameters to improve the model’s F-score." }, { "code": null, "e": 18639, "s": 18615, "text": "Choosing the Best Model" }, { "code": null, "e": 18852, "s": 18639, "text": "Based on the results of the evaluation, the most appropiate model to identify potential donors is the Random Forest Classifier as it yields the same F-score of the Support Vector Classifier but in much less time." }, { "code": null, "e": 19036, "s": 18852, "text": "This is coherent with our knowledge of the algorithm as it is a very good choice when dealing with high-dimensional datasets, in other words, datasets with a large number of features." }, { "code": null, "e": 19144, "s": 19036, "text": "So among the evaluated models, this is the more efficient one and best the suited to work with our dataset." }, { "code": null, "e": 19187, "s": 19144, "text": "Describing Random Forest in Layman’s Terms" }, { "code": null, "e": 19684, "s": 19187, "text": "To understand Random Forests Classificators we need first to introduce the concept of Decision Trees. A Decision Tree is a flowchart-like structure, in which each internal node represents a test on an attribute of the dataset, each brand represents the outcome of the test and each leaf represents a class label. So the algorithm will make the tests on the data, finding out which are the most relevant features of the dataset to predict a certain outcome, and separating accordingly the dataset." }, { "code": null, "e": 19785, "s": 19684, "text": "The following is an example of a decision tree to decide wheter or not you lend your car to someone:" }, { "code": null, "e": 20286, "s": 19785, "text": "A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy of the model, and control overfitting by preventing it to become too complex and unable to generalize on unseen data. It randomly selects a number of features and trains each decision tree classifier in every sub-set of the features. Then, it each decision tree to make predictions by making them vote for the correct label." }, { "code": null, "e": 20433, "s": 20286, "text": "Random Forests classifiers are quite popular in classification problems due to its simplicity to use, efficiency and its good predicting accuracy." }, { "code": null, "e": 20447, "s": 20433, "text": "Model Tunning" }, { "code": null, "e": 20507, "s": 20447, "text": "We will now fine tune the chosen model, using GridSearchCV." }, { "code": null, "e": 21918, "s": 20507, "text": "# Import the necessary librariesfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorer# Initialize the classifierclf = RandomForestClassifier(random_state = 42)# Create the parameters list parameters = { 'max_depth': [10,20,30,40], 'max_features': [2, 3], 'min_samples_leaf': [3, 4, 5], 'min_samples_split': [8, 10, 12], 'n_estimators': [50,100,150]}# Make an fbeta_score scoring object using make_scorer()scorer = make_scorer(fbeta_score, beta=0.5)# Perform grid search on the classifier grid_obj = GridSearchCV(estimator=clf, param_grid=parameters, scoring=scorer)# Fit the grid search object to the training data grid_fit = grid_obj.fit(X_train, y_train)# Get the estimatorbest_clf = grid_fit.best_estimator_# Make predictions using the unoptimized and modelpredictions = (clf.fit(X_train, y_train)).predict(X_test)best_predictions = best_clf.predict(X_test)# Report the before-and-afterscoresprint(\"Unoptimized model\\n------\")print(\"Accuracy score on testing data {:.4f}\".format(accuracy_score(y_test, predictions)))print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, predictions, beta = 0.5)))print(\"\\nOptimized Model\\n------\")print(\"Final accuracy score on the testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))print(\"Final F-score on the testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))" }, { "code": null, "e": 21969, "s": 21918, "text": "# Show the best classifier hyperparametersbest_clf" }, { "code": null, "e": 21982, "s": 21969, "text": "Observations" }, { "code": null, "e": 22077, "s": 21982, "text": "The optimized model’s accuracy and F-score on testing data are: 84.8% and 71.38% respectively." }, { "code": null, "e": 22187, "s": 22077, "text": "These scores are slightly better than the ones of the unoptimized model but the computing time is far larger." }, { "code": null, "e": 22351, "s": 22187, "text": "The naive predictor benchmarks for the accuracy and F-score are 24.78% and 29.27% respectively, which are much worse than the ones obtained with the trained model." }, { "code": null, "e": 22377, "s": 22351, "text": "Extra: Feature Importance" }, { "code": null, "e": 22703, "s": 22377, "text": "An important task when performing supervised learning on a dataset like his one is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do." }, { "code": null, "e": 22875, "s": 22703, "text": "In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than $50,000." }, { "code": null, "e": 23013, "s": 22875, "text": "Intuitively, of the 13 features available on the original datasetwe can infer that the most important ones for predicting the income are:" }, { "code": null, "e": 23020, "s": 23013, "text": "1) age" }, { "code": null, "e": 23033, "s": 23020, "text": "2) education" }, { "code": null, "e": 23051, "s": 23033, "text": "3) native-country" }, { "code": null, "e": 23065, "s": 23051, "text": "4) occupation" }, { "code": null, "e": 23083, "s": 23065, "text": "5) hours per week" }, { "code": null, "e": 23124, "s": 23083, "text": "The rank’s order logic is the following:" }, { "code": null, "e": 23250, "s": 23124, "text": "It is likely that a person’s income would increase over the years and older people tend to earn more money than younger ones." }, { "code": null, "e": 23510, "s": 23250, "text": "In additon, people who have higher education tend to get higher paid jobs and this is a factor that is also heavily related with the native country as, usually, people that are native of economically stronger countries tend to have access to higher education." }, { "code": null, "e": 23638, "s": 23510, "text": "Occupation is an important feature to take into consideration as yearly income vary a lot depending on the industry and sector." }, { "code": null, "e": 23721, "s": 23638, "text": "Finally, hours per week as normally, people who work more hours tend to earn more." }, { "code": null, "e": 23842, "s": 23721, "text": "We will now chek the accuracy of our logic by passing our data through a model that hast the feature_importance_ method:" }, { "code": null, "e": 24168, "s": 23842, "text": "# Import Ada Boost Classifierfrom sklearn.ensemble import AdaBoostClassifier# Train the supervised model on the training model = AdaBoostClassifier().fit(X_train, y_train)# Extract the feature importances using .feature_importances_ importances = model.feature_importances_# Plotvs.feature_plot(importances, X_train, y_train)" }, { "code": null, "e": 24420, "s": 24168, "text": "The intution followed in the previous section was partially right as the AdaBoost tests shows that feautures like age, hours per week and education are quite relevant to predict the income. However, we didn’t indentified capital-loss and capital-gain." }, { "code": null, "e": 24438, "s": 24420, "text": "Feature Selection" }, { "code": null, "e": 24481, "s": 24438, "text": "Now it is reasonable to ask the following:" }, { "code": null, "e": 24573, "s": 24481, "text": "How does a model perform if we only use a subset of all the available features in the data?" }, { "code": null, "e": 24997, "s": 24573, "text": "With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of all features present in the data. This hints that we can attempt to reduce the feature space and simplify the information required for the model to learn." }, { "code": null, "e": 25996, "s": 24997, "text": "# Import functionality for cloning a modelfrom sklearn.base import clone# Reduce the feature spaceX_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]# Train on the \"best\" model found from grid search earlierclf = (clone(best_clf)).fit(X_train_reduced, y_train)# Make new predictionsreduced_predictions = clf.predict(X_test_reduced)# Report scores from the final model using both versions of dataprint(\"Final Model trained on full data\\n------\")print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, best_predictions)))print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, best_predictions, beta = 0.5)))print(\"\\nFinal Model trained on reduced data\\n------\")print(\"Accuracy on testing data: {:.4f}\".format(accuracy_score(y_test, reduced_predictions)))print(\"F-score on testing data: {:.4f}\".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))" }, { "code": null, "e": 26045, "s": 25996, "text": "Observations of the Effects of Feature Selection" }, { "code": null, "e": 26166, "s": 26045, "text": "Both accuracy and f-score are lower on the reduced data than on the original dataset. Specially f-score 71.38% vs 67.57%" }, { "code": null, "e": 26455, "s": 26166, "text": "Considering the metrics obtained in the evaluations made on the default model, the optimized model and the reduced dataset, the best option would be to use the default model version with the complete dataset as it yields a good combination of accuracy and f-score in a good training time." }, { "code": null, "e": 26671, "s": 26455, "text": "Throughout this article we made a machine learning classification project from end-to-end and we learned and obtained several insights about classification models and the keys to develop one with a good performance." }, { "code": null, "e": 26808, "s": 26671, "text": "This was the third of the machine learning projects that have been explained inthis series. If you liked it, check out the previous one:" }, { "code": null, "e": 26827, "s": 26808, "text": "Regression Project" }, { "code": null, "e": 26847, "s": 26827, "text": "Naive Bayes Project" }, { "code": null, "e": 26973, "s": 26847, "text": "Stay tuned for the next article! Which will be an introduction to the theory and concepts regarding to Unsupervised Learning." }, { "code": null, "e": 27082, "s": 26973, "text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here." } ]
How to convert data.table object into a matrix in R?
A data.table object is very similar to a data frame in R, therefore, converting a data.table object to a matrix is not a difficult job. We just need to use as.matrix function and store the data.table object into a new object that will belong to the matrix, otherwise R will not be able to convert the data.object to a matrix. For example, if we have a data.table object DT then to convert it into a matrix, we should use the below example code − DT_matrix<-as.matrix(DT) Loading data.table package − library(data.table) Creating a data.table object − x1<-rnorm(20,1,0.04) x2<-rnorm(20,5,1.2) x3<-runif(20,5,10) x4<-runif(20,1,5) DT1<-data.table(x1,x2,x3,x4) DT1 x1 x2 x3 x4 1: 0.9785610 7.345365 8.079572 4.289080 2: 0.9787770 6.684993 6.842196 3.420399 3: 0.9936527 5.076511 6.584490 4.339317 4: 0.9585088 6.348905 5.256956 1.041050 5: 1.0172288 6.076759 6.456343 3.964968 6: 1.0199971 6.384019 6.444665 2.477480 7: 1.0027680 5.189908 6.352739 3.358625 8: 1.0013410 7.480771 6.236253 3.704360 9: 0.9638484 3.173219 6.768095 2.710411 10: 0.9771605 4.072879 5.269356 3.689747 11: 0.9768464 3.898211 8.212824 1.230352 12: 1.0322361 4.964122 8.062670 2.333302 13: 0.9730514 2.746493 7.991256 1.319675 14: 1.0157617 4.032643 7.324038 3.883257 15: 1.0167210 6.994750 5.123840 3.157113 16: 0.9526550 5.292459 8.401666 2.362798 17: 1.0022340 4.753125 6.175266 3.900407 18: 1.0456185 6.001135 8.018412 3.324448 19: 1.1422387 5.121760 5.340800 2.348761 20: 0.9269784 5.893736 5.754917 1.940769 is.matrix(DT1_matrix) [1] TRUE Let’s have a look at another example − y1<-rpois(20,2) y2<-rpois(20,5) y3<-rpois(20,8) y4<-rpois(20,10) y5<-sample(0:9,20,replace=TRUE) DT2<-data.table(y1,y2,y3,y4,y5) DT2 y1 y2 y3 y4 y5 1: 2 5 12 12 7 2: 2 7 9 8 1 3: 2 5 3 9 2 4: 0 0 10 12 9 5: 2 3 5 8 8 6: 4 7 6 8 9 7: 2 7 8 9 0 8: 0 7 8 11 1 9: 3 6 7 8 2 10: 0 3 8 9 1 11: 2 7 9 9 2 12: 3 4 8 7 7 13: 0 1 10 14 8 14: 1 6 7 5 9 15: 3 3 12 14 6 16: 0 4 8 8 4 17: 1 7 9 13 2 18: 5 1 14 11 7 19: 1 4 14 9 6 20: 3 5 8 10 1 Converting data.table object into a matrix object − DT2_matrix<-as.matrix(DT2) DT2_matrix y1 y2 y3 y4 y5 [1,] 2 5 12 12 7 [2,] 2 7 9 8 1 [3,] 2 5 3 9 2 [4,] 0 0 10 12 9 [5,] 2 3 5 8 8 [6,] 4 7 6 8 9 [7,] 2 7 8 9 0 [8,] 0 7 8 11 1 [9,] 3 6 7 8 2 [10,] 0 3 8 9 1 [11,] 2 7 9 9 2 [12,] 3 4 8 7 7 [13,] 0 1 10 14 8 [14,] 1 6 7 5 9 [15,] 3 3 12 14 6 [16,] 0 4 8 8 4 [17,] 1 7 9 13 2 [18,] 5 1 14 11 7 [19,] 1 4 14 9 6 [20,] 3 5 8 10 1 is.matrix(DT2_matrix) [1] TRUE
[ { "code": null, "e": 1508, "s": 1062, "text": "A data.table object is very similar to a data frame in R, therefore, converting a data.table object to a matrix is not a difficult job. We just need to use as.matrix function and store the data.table object into a new object that will belong to the matrix, otherwise R will not be able to convert the data.object to a matrix. For example, if we have a data.table object DT then to convert it into a matrix, we should use the below example code −" }, { "code": null, "e": 1533, "s": 1508, "text": "DT_matrix<-as.matrix(DT)" }, { "code": null, "e": 1562, "s": 1533, "text": "Loading data.table package −" }, { "code": null, "e": 1582, "s": 1562, "text": "library(data.table)" }, { "code": null, "e": 1613, "s": 1582, "text": "Creating a data.table object −" }, { "code": null, "e": 1724, "s": 1613, "text": "x1<-rnorm(20,1,0.04)\nx2<-rnorm(20,5,1.2)\nx3<-runif(20,5,10)\nx4<-runif(20,1,5)\nDT1<-data.table(x1,x2,x3,x4)\nDT1" }, { "code": null, "e": 2547, "s": 1724, "text": "x1 x2 x3 x4\n1: 0.9785610 7.345365 8.079572 4.289080\n2: 0.9787770 6.684993 6.842196 3.420399\n3: 0.9936527 5.076511 6.584490 4.339317\n4: 0.9585088 6.348905 5.256956 1.041050\n5: 1.0172288 6.076759 6.456343 3.964968\n6: 1.0199971 6.384019 6.444665 2.477480\n7: 1.0027680 5.189908 6.352739 3.358625\n8: 1.0013410 7.480771 6.236253 3.704360\n9: 0.9638484 3.173219 6.768095 2.710411\n10: 0.9771605 4.072879 5.269356 3.689747\n11: 0.9768464 3.898211 8.212824 1.230352\n12: 1.0322361 4.964122 8.062670 2.333302\n13: 0.9730514 2.746493 7.991256 1.319675\n14: 1.0157617 4.032643 7.324038 3.883257\n15: 1.0167210 6.994750 5.123840 3.157113\n16: 0.9526550 5.292459 8.401666 2.362798\n17: 1.0022340 4.753125 6.175266 3.900407\n18: 1.0456185 6.001135 8.018412 3.324448\n19: 1.1422387 5.121760 5.340800 2.348761\n20: 0.9269784 5.893736 5.754917 1.940769" }, { "code": null, "e": 2570, "s": 2547, "text": "is.matrix(DT1_matrix) " }, { "code": null, "e": 2579, "s": 2570, "text": "[1] TRUE" }, { "code": null, "e": 2618, "s": 2579, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2751, "s": 2618, "text": "y1<-rpois(20,2)\ny2<-rpois(20,5)\ny3<-rpois(20,8)\ny4<-rpois(20,10)\ny5<-sample(0:9,20,replace=TRUE)\nDT2<-data.table(y1,y2,y3,y4,y5)\nDT2" }, { "code": null, "e": 3179, "s": 2751, "text": " y1 y2 y3 y4 y5\n1: 2 5 12 12 7\n2: 2 7 9 8 1\n3: 2 5 3 9 2\n4: 0 0 10 12 9\n5: 2 3 5 8 8\n6: 4 7 6 8 9\n7: 2 7 8 9 0\n8: 0 7 8 11 1\n9: 3 6 7 8 2\n10: 0 3 8 9 1\n11: 2 7 9 9 2\n12: 3 4 8 7 7\n13: 0 1 10 14 8\n14: 1 6 7 5 9\n15: 3 3 12 14 6\n16: 0 4 8 8 4\n17: 1 7 9 13 2\n18: 5 1 14 11 7\n19: 1 4 14 9 6\n20: 3 5 8 10 1" }, { "code": null, "e": 3231, "s": 3179, "text": "Converting data.table object into a matrix object −" }, { "code": null, "e": 3269, "s": 3231, "text": "DT2_matrix<-as.matrix(DT2)\nDT2_matrix" }, { "code": null, "e": 3666, "s": 3269, "text": " y1 y2 y3 y4 y5\n[1,] 2 5 12 12 7\n[2,] 2 7 9 8 1\n[3,] 2 5 3 9 2\n[4,] 0 0 10 12 9\n[5,] 2 3 5 8 8\n[6,] 4 7 6 8 9\n[7,] 2 7 8 9 0\n[8,] 0 7 8 11 1\n[9,] 3 6 7 8 2\n[10,] 0 3 8 9 1\n[11,] 2 7 9 9 2\n[12,] 3 4 8 7 7\n[13,] 0 1 10 14 8\n[14,] 1 6 7 5 9\n[15,] 3 3 12 14 6\n[16,] 0 4 8 8 4\n[17,] 1 7 9 13 2\n[18,] 5 1 14 11 7\n[19,] 1 4 14 9 6\n[20,] 3 5 8 10 1" }, { "code": null, "e": 3689, "s": 3666, "text": "is.matrix(DT2_matrix) " }, { "code": null, "e": 3698, "s": 3689, "text": "[1] TRUE" } ]
Free base-maps for static maps using Geopandas and Contextily | by Wathela Hamed | Towards Data Science
Contextily is a package for contextual tiles in Python. In this quick tutorial, I am going to show you how to use contextily along with Geopandas in Jupyter Notebook to produce some nice maps. First of all, we need to make sure these packages are installed, go to your anaconda prompt and type: conda install -c conda-forge geopandasconda install -c conda-forge contextily I am assuming you already have matplotlib package installed, if not make sure you install it first. conda install -c conda-forge matplotlib Now we need to import our packages into a notebook: import geopandas as gpdimport contextily as ctximport matplotlib.pyplot as plt In this tutorial, I am going to use a conflict points data from North Darfur State/Sudan and its boundary shape-files, this data and the full code for this tutorial can be found at Github. # Read in the conflict points and the boundary shape files using geopandasconf_data = gpd.read_file("NorthDarfurConf.shp")ND_Boundary = gpd.read_file("NorthDarfurBoundary.shp") For a quick exploration of the data, you can simply print the head of the geo-dataframes to see what columns they have. conf_data.columns ND_Boundary.columns We only need the event_type column from the conflict geo-dataframe which contains the type of the recorded event. It’s only one line of code to show this data: # we specify the column that is going to be used for the symbologyconf_data.plot(column = 'event_type'); To make it a bit nicer, some parameters need to be set, also we going to use the boundary geo-dataframe as well to show the boundary of the state. But first of all, we need to customize the colors of the plot (if you have realized it was randomly generated). Simply we will create a dictionary for our unique values in the even_type column and assign each value a unique custom color code. # get the uniques values in event_type columncategories = conf_data.event_type.unique()# create a list for our custom colorsc = ['m', 'k', 'g', 'r', 'y', 'c']# create a dictionary to combine both lists, categories are keys and # color codes are valuescolorDict = dict(zip(categories,c))print(colorDict) To plot our points with our custom colors we will need to group the conf_data geo-dataframe by the event_type column so each unique event type gets its assigned color from the color dictionary. # plot the state's boundary with black edge color only and line width of 2ax = ND_Boundary.geometry.boundary.plot(figsize = (10,15), color = None, edgecolor = 'K', linewidth=2)# Loop through each event type group for eventType, data in conf_data.groupby('event_type'): color = colorDict[eventType] data.plot(ax = ax, color = color, label = eventType) Now we are ready to explore contextily and see how we can use it to include a base-map in our map. Contextily has a whole list of providers. They are all stored as dictionaries so you can easily explore and switch between them in python: print(ctx.providers.keys()) To see which tile each provider contains, you use the provider name to print its tiles. For example let’s see what tiles does Open Street Map provider has: print(ctx.providers.OpenStreetMap.keys()) To add a base-map to our previous map we only need to add one line of code to the previous code, where we specify: Axis: To make sure we plotting everything together. Coordinate reference system (crs): For the crs, will use the same crs of conf_data or ND_Boundary (both have the same crs) otherwise it won’t work. Provider: for instance the Open Street Map with Mapnik tile. # add open street map basemapctx.add_basemap(ax, crs = ND_Boundary.crs, url = ctx.providers.OpenStreetMap.Mapnik) Finally, will add a legend and title to our map: ax.legend(bbox_to_anchor = (0.31,1), prop={'size':10}) # set legend's position and sizeax.set(title="Conflict in North Darfur/Sudan (1997-2020)") # add a title to the mapax.set_axis_off() # remove the axis ticks plt.tight_layout() # adjust the padding between figure edgesplt.savefig('norhtDarfur_conf_OSM_Map.png')# Save the map as an imageplt.show() Here are some other providers:
[ { "code": null, "e": 466, "s": 171, "text": "Contextily is a package for contextual tiles in Python. In this quick tutorial, I am going to show you how to use contextily along with Geopandas in Jupyter Notebook to produce some nice maps. First of all, we need to make sure these packages are installed, go to your anaconda prompt and type:" }, { "code": null, "e": 544, "s": 466, "text": "conda install -c conda-forge geopandasconda install -c conda-forge contextily" }, { "code": null, "e": 644, "s": 544, "text": "I am assuming you already have matplotlib package installed, if not make sure you install it first." }, { "code": null, "e": 684, "s": 644, "text": "conda install -c conda-forge matplotlib" }, { "code": null, "e": 736, "s": 684, "text": "Now we need to import our packages into a notebook:" }, { "code": null, "e": 815, "s": 736, "text": "import geopandas as gpdimport contextily as ctximport matplotlib.pyplot as plt" }, { "code": null, "e": 1004, "s": 815, "text": "In this tutorial, I am going to use a conflict points data from North Darfur State/Sudan and its boundary shape-files, this data and the full code for this tutorial can be found at Github." }, { "code": null, "e": 1181, "s": 1004, "text": "# Read in the conflict points and the boundary shape files using geopandasconf_data = gpd.read_file(\"NorthDarfurConf.shp\")ND_Boundary = gpd.read_file(\"NorthDarfurBoundary.shp\")" }, { "code": null, "e": 1301, "s": 1181, "text": "For a quick exploration of the data, you can simply print the head of the geo-dataframes to see what columns they have." }, { "code": null, "e": 1319, "s": 1301, "text": "conf_data.columns" }, { "code": null, "e": 1339, "s": 1319, "text": "ND_Boundary.columns" }, { "code": null, "e": 1499, "s": 1339, "text": "We only need the event_type column from the conflict geo-dataframe which contains the type of the recorded event. It’s only one line of code to show this data:" }, { "code": null, "e": 1604, "s": 1499, "text": "# we specify the column that is going to be used for the symbologyconf_data.plot(column = 'event_type');" }, { "code": null, "e": 1994, "s": 1604, "text": "To make it a bit nicer, some parameters need to be set, also we going to use the boundary geo-dataframe as well to show the boundary of the state. But first of all, we need to customize the colors of the plot (if you have realized it was randomly generated). Simply we will create a dictionary for our unique values in the even_type column and assign each value a unique custom color code." }, { "code": null, "e": 2297, "s": 1994, "text": "# get the uniques values in event_type columncategories = conf_data.event_type.unique()# create a list for our custom colorsc = ['m', 'k', 'g', 'r', 'y', 'c']# create a dictionary to combine both lists, categories are keys and # color codes are valuescolorDict = dict(zip(categories,c))print(colorDict)" }, { "code": null, "e": 2491, "s": 2297, "text": "To plot our points with our custom colors we will need to group the conf_data geo-dataframe by the event_type column so each unique event type gets its assigned color from the color dictionary." }, { "code": null, "e": 2850, "s": 2491, "text": "# plot the state's boundary with black edge color only and line width of 2ax = ND_Boundary.geometry.boundary.plot(figsize = (10,15), color = None, edgecolor = 'K', linewidth=2)# Loop through each event type group for eventType, data in conf_data.groupby('event_type'): color = colorDict[eventType] data.plot(ax = ax, color = color, label = eventType)" }, { "code": null, "e": 3088, "s": 2850, "text": "Now we are ready to explore contextily and see how we can use it to include a base-map in our map. Contextily has a whole list of providers. They are all stored as dictionaries so you can easily explore and switch between them in python:" }, { "code": null, "e": 3116, "s": 3088, "text": "print(ctx.providers.keys())" }, { "code": null, "e": 3272, "s": 3116, "text": "To see which tile each provider contains, you use the provider name to print its tiles. For example let’s see what tiles does Open Street Map provider has:" }, { "code": null, "e": 3314, "s": 3272, "text": "print(ctx.providers.OpenStreetMap.keys())" }, { "code": null, "e": 3429, "s": 3314, "text": "To add a base-map to our previous map we only need to add one line of code to the previous code, where we specify:" }, { "code": null, "e": 3481, "s": 3429, "text": "Axis: To make sure we plotting everything together." }, { "code": null, "e": 3629, "s": 3481, "text": "Coordinate reference system (crs): For the crs, will use the same crs of conf_data or ND_Boundary (both have the same crs) otherwise it won’t work." }, { "code": null, "e": 3690, "s": 3629, "text": "Provider: for instance the Open Street Map with Mapnik tile." }, { "code": null, "e": 3804, "s": 3690, "text": "# add open street map basemapctx.add_basemap(ax, crs = ND_Boundary.crs, url = ctx.providers.OpenStreetMap.Mapnik)" }, { "code": null, "e": 3853, "s": 3804, "text": "Finally, will add a legend and title to our map:" }, { "code": null, "e": 4205, "s": 3853, "text": "ax.legend(bbox_to_anchor = (0.31,1), prop={'size':10}) # set legend's position and sizeax.set(title=\"Conflict in North Darfur/Sudan (1997-2020)\") # add a title to the mapax.set_axis_off() # remove the axis ticks plt.tight_layout() # adjust the padding between figure edgesplt.savefig('norhtDarfur_conf_OSM_Map.png')# Save the map as an imageplt.show()" } ]
Anonymous classes in C++
Anonymous entity is anything that is defined without a name. A class with no name provided is known as an anonymous class in c++. An anonymous class is a special class with one basic property. As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block. As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block. The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function. The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function. class { //data members // member fucntions } Some programming to illustrate the working of an anonymous class in c++. Creating an anonymous class and defining and using its single objects −We will define an anonymous class and declare its objects using which we will use the members of the class. Creating an anonymous class and defining and using its single objects − We will define an anonymous class and declare its objects using which we will use the members of the class. Live Demo #include <iostream> using namespace std; class{ int value; public: void setData(int i){ this->value = i; } void printvalues(){ cout<<"Value : "<<this->value<<endl; } } obj1; int main(){ obj1.setData(10); obj1.printvalues(); return 0; } Value : 10 Creating an anonymous class and defining and using its two objects −We can have multiple objects of an anonymous class and use them in our code. The below program show the working − Creating an anonymous class and defining and using its two objects − We can have multiple objects of an anonymous class and use them in our code. The below program show the working − Live Demo #include <iostream> using namespace std; class{ int value; public: void setData(int i){ this->value = i; } void print(){ cout<<"Value : "<<this->value<<endl; } } obj1,obj2; int main(){ cout<<"Object 1 \n"; obj1.setData(10); obj1.print(); cout<<"Object 2 \n"; obj1.setData(12); obj1.print(); return 0; } Object 1 Value : 10 Object 2 Value : 12
[ { "code": null, "e": 1255, "s": 1062, "text": "Anonymous entity is anything that is defined without a name. A class with no name provided is known as an anonymous class in c++. An anonymous class is a special class with one basic property." }, { "code": null, "e": 1399, "s": 1255, "text": "As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block." }, { "code": null, "e": 1543, "s": 1399, "text": "As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block." }, { "code": null, "e": 1685, "s": 1543, "text": "The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function." }, { "code": null, "e": 1827, "s": 1685, "text": "The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function." }, { "code": null, "e": 1878, "s": 1827, "text": "class {\n //data members\n // member fucntions\n}" }, { "code": null, "e": 1951, "s": 1878, "text": "Some programming to illustrate the working of an anonymous class in c++." }, { "code": null, "e": 2130, "s": 1951, "text": "Creating an anonymous class and defining and using its single objects −We will define an anonymous class and declare its objects using which we will use the members of the class." }, { "code": null, "e": 2202, "s": 2130, "text": "Creating an anonymous class and defining and using its single objects −" }, { "code": null, "e": 2310, "s": 2202, "text": "We will define an anonymous class and declare its objects using which we will use the members of the class." }, { "code": null, "e": 2321, "s": 2310, "text": " Live Demo" }, { "code": null, "e": 2597, "s": 2321, "text": "#include <iostream>\nusing namespace std;\nclass{\n int value;\n public:\n void setData(int i){\n this->value = i;\n }\n void printvalues(){\n cout<<\"Value : \"<<this->value<<endl;\n }\n}\n obj1;\nint main(){\n obj1.setData(10);\n obj1.printvalues();\n return 0;\n}" }, { "code": null, "e": 2608, "s": 2597, "text": "Value : 10" }, { "code": null, "e": 2790, "s": 2608, "text": "Creating an anonymous class and defining and using its two objects −We can have multiple objects of an anonymous class and use them in our code. The below program show the working −" }, { "code": null, "e": 2859, "s": 2790, "text": "Creating an anonymous class and defining and using its two objects −" }, { "code": null, "e": 2973, "s": 2859, "text": "We can have multiple objects of an anonymous class and use them in our code. The below program show the working −" }, { "code": null, "e": 2984, "s": 2973, "text": " Live Demo" }, { "code": null, "e": 3339, "s": 2984, "text": "#include <iostream>\nusing namespace std;\nclass{\n int value;\n public:\n void setData(int i){\n this->value = i;\n }\n void print(){\n cout<<\"Value : \"<<this->value<<endl;\n }\n}\n obj1,obj2;\nint main(){\n cout<<\"Object 1 \\n\";\n obj1.setData(10);\n obj1.print();\n cout<<\"Object 2 \\n\";\n obj1.setData(12);\n obj1.print();\n return 0;\n}" }, { "code": null, "e": 3379, "s": 3339, "text": "Object 1\nValue : 10\nObject 2\nValue : 12" } ]
Finding Position | Practice | GeeksforGeeks
Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue. Example 1: Input: n = 5 Output: 4 Explanation: 1,2,3,4,5 -> 2,4 -> 4. Example 2: Input: n = 9 Output: 8 Explanation: 1,2,3,4,5,6,7,8,9 ->2,4,6,8 -> 4,8 -> 8. Your Task: You dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left. Expected Time Complexity: O(logn) Expected Auxiliary Space: O(1) Constraints: 1<= n <=108 0 debasishtewary53 weeks ago 0.11/15.52 static long find(long i,long n){ if(i>n) return i/2; else{ i=i*2; return find(i,n); } } static long nthPosition(long n){ // code here return Solution.find(1,n); } 0 rajsinh21812 months ago Easy Recursive solution long long int nthPosition(long long int n){ if(n==1) return 1; return nthPosition(n/2)*2; } 0 abhishekbajpaiamity2 months ago class Solution { static long nthPosition(long n){ int value=(int)(Math.log(n) /Math.log(2)); int pow=(int)Math.pow(2,value); return pow; }} 0 aminul012 months ago Simple java solution 0.1 time taken class Solution { static long nthPosition(long n){ // code here long ans = 1; while (n != 1) { ans = 2 * ans; n /= 2; } return ans; }} 0 harshitsharma60913 months ago long long int nthPosition(long long int n) { if(n<2) return 0; while(( n & (n-1)) !=0) { n=n&(n-1); } return n; } 0 uday_wahi3 months ago java simple one liner solution time complexity : O(1) time 0.1/15.5 static long nthPosition(long n){ return (long) Math.pow(2,(long) (Math.log(n)/Math.log(2))); } 0 programmingdopractice3 months ago long long int nthPosition(long long int n){ // code here int len = log2(n); return pow(2,len); } Didn't do anything 0 user_990i4 months ago Iterative solution in 0 sec execution class Solution { public: long long int nthPosition(long long int n){ long long int count =1; while(n!=1){ count=2*count; n=n/2; } return count; }}; 0 user_990i4 months ago class Solution { public: long long int nthPosition(long long int n){ if(n==1){ return 1; } return nthPosition(n/2)*2; }}; +1 ankulchaudhary244 months ago A simlple and very efficeint recursive solution long long int nthPosition(long long int n){ if(n==1) return 1; else return 2*nthPosition(n/2); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 596, "s": 238, "text": "Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.\n\nExample 1:" }, { "code": null, "e": 657, "s": 596, "text": "Input: n = 5\nOutput: 4 \nExplanation: 1,2,3,4,5 -> 2,4 -> 4.\n" }, { "code": null, "e": 669, "s": 657, "text": "\nExample 2:" }, { "code": null, "e": 748, "s": 669, "text": "Input: n = 9\nOutput: 8\nExplanation: 1,2,3,4,5,6,7,8,9\n->2,4,6,8 -> 4,8 -> 8. \n" }, { "code": null, "e": 1039, "s": 748, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left.\n\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<= n <=108" }, { "code": null, "e": 1041, "s": 1039, "text": "0" }, { "code": null, "e": 1068, "s": 1041, "text": "debasishtewary53 weeks ago" }, { "code": null, "e": 1079, "s": 1068, "text": "0.11/15.52" }, { "code": null, "e": 1303, "s": 1079, "text": "static long find(long i,long n){ if(i>n) return i/2; else{ i=i*2; return find(i,n); } } static long nthPosition(long n){ // code here return Solution.find(1,n); }" }, { "code": null, "e": 1305, "s": 1303, "text": "0" }, { "code": null, "e": 1329, "s": 1305, "text": "rajsinh21812 months ago" }, { "code": null, "e": 1353, "s": 1329, "text": "Easy Recursive solution" }, { "code": null, "e": 1485, "s": 1353, "text": "long long int nthPosition(long long int n){\n if(n==1)\n return 1;\n \n return nthPosition(n/2)*2;\n }" }, { "code": null, "e": 1487, "s": 1485, "text": "0" }, { "code": null, "e": 1519, "s": 1487, "text": "abhishekbajpaiamity2 months ago" }, { "code": null, "e": 1679, "s": 1519, "text": "class Solution { static long nthPosition(long n){ int value=(int)(Math.log(n) /Math.log(2)); int pow=(int)Math.pow(2,value); return pow; }}" }, { "code": null, "e": 1681, "s": 1679, "text": "0" }, { "code": null, "e": 1702, "s": 1681, "text": "aminul012 months ago" }, { "code": null, "e": 1738, "s": 1702, "text": "Simple java solution 0.1 time taken" }, { "code": null, "e": 1937, "s": 1738, "text": "class Solution { static long nthPosition(long n){ // code here long ans = 1; while (n != 1) { ans = 2 * ans; n /= 2; } return ans; }}" }, { "code": null, "e": 1939, "s": 1937, "text": "0" }, { "code": null, "e": 1969, "s": 1939, "text": "harshitsharma60913 months ago" }, { "code": null, "e": 2128, "s": 1969, "text": " long long int nthPosition(long long int n) { if(n<2) return 0; while(( n & (n-1)) !=0) { n=n&(n-1); } return n; }" }, { "code": null, "e": 2130, "s": 2128, "text": "0" }, { "code": null, "e": 2152, "s": 2130, "text": "uday_wahi3 months ago" }, { "code": null, "e": 2183, "s": 2152, "text": "java simple one liner solution" }, { "code": null, "e": 2206, "s": 2183, "text": "time complexity : O(1)" }, { "code": null, "e": 2220, "s": 2206, "text": "time 0.1/15.5" }, { "code": null, "e": 2327, "s": 2222, "text": "static long nthPosition(long n){\n return (long) Math.pow(2,(long) (Math.log(n)/Math.log(2)));\n }" }, { "code": null, "e": 2329, "s": 2327, "text": "0" }, { "code": null, "e": 2363, "s": 2329, "text": "programmingdopractice3 months ago" }, { "code": null, "e": 2511, "s": 2363, "text": "long long int nthPosition(long long int n){\n // code here\n int len = log2(n);\n return pow(2,len);\n }\n Didn't do anything" }, { "code": null, "e": 2513, "s": 2511, "text": "0" }, { "code": null, "e": 2535, "s": 2513, "text": "user_990i4 months ago" }, { "code": null, "e": 2573, "s": 2535, "text": "Iterative solution in 0 sec execution" }, { "code": null, "e": 2747, "s": 2573, "text": "class Solution { public: long long int nthPosition(long long int n){ long long int count =1; while(n!=1){ count=2*count; n=n/2; } return count; }};" }, { "code": null, "e": 2749, "s": 2747, "text": "0" }, { "code": null, "e": 2771, "s": 2749, "text": "user_990i4 months ago" }, { "code": null, "e": 2916, "s": 2771, "text": "class Solution { public: long long int nthPosition(long long int n){ if(n==1){ return 1; } return nthPosition(n/2)*2; }};" }, { "code": null, "e": 2919, "s": 2916, "text": "+1" }, { "code": null, "e": 2948, "s": 2919, "text": "ankulchaudhary244 months ago" }, { "code": null, "e": 2996, "s": 2948, "text": "A simlple and very efficeint recursive solution" }, { "code": null, "e": 3121, "s": 2996, "text": " long long int nthPosition(long long int n){ if(n==1) return 1; else return 2*nthPosition(n/2); }" }, { "code": null, "e": 3267, "s": 3121, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3303, "s": 3267, "text": " Login to access your submissions. " }, { "code": null, "e": 3313, "s": 3303, "text": "\nProblem\n" }, { "code": null, "e": 3323, "s": 3313, "text": "\nContest\n" }, { "code": null, "e": 3386, "s": 3323, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3534, "s": 3386, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3742, "s": 3534, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3848, "s": 3742, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Use Environment Variable in your next Golang Project | by Shubham Chadokar | Towards Data Science
When it comes to creating a production-grade application, using the environment variable in the application is de facto. Read my Latest articles here. Suppose you have an application with many features and each feature need to access the Database. You configured all the DB information like DBURL, DBNAME, USERNAME and PASSWORD in each feature. There are a few major disadvantages to this approach, there can be many. You’re entering all the information in the code. Now, all the unauthorized person also have access to the DB. If you’re using code versioning tool like git then the details of your DB will go public once you push the code. If you are changing a single variable then you have to change in all the features. There is a high possibility that you’ll miss one or two. 😌 been there You can categorize the environment variables like PROD, DEV, or TEST. Just prefix the variable with the environment. At the start, it might look like some extra work, but this will reward you a lot in your project. ⚠️ Just don’t forget to include your environment files in the .gitignore. It is time for some action. 🔨 In this tutorial, we will access environment variables in 3 different ways. You can use according to your requirement. os package godotenv package viper package Create a project go-env-ways outside the $GOPATH. Open the terminal inside the project root directory, and run the below command. go mod init go-env-ways This module will keep a record of all the packages and their version used in the project. It is similar to package.json in nodejs. Let’s start with the easiest one, using os package. Golang provides os package, an easy way to configure and access the environment variable. To set the environment variable, os.Setenv(key, value) To get the environment variable, value := os.Getenv(key) Create a new file main.go inside the project. package mainimport ( "fmt" "os")// use os package to get the env variable which is already setfunc envVariable(key string) string { // set env variable using os package os.Setenv(key, "gopher") // return the env variable using os package return os.Getenv(key)}func main() { // os package value := envVariable("name") fmt.Printf("os package: name = %s \n", value) fmt.Printf("environment = %s \n", os.Getenv("APP_ENV"))} Run the below command to check. APP_ENV=prod go run main.go// Outputos package: name = gopherenvironment = prod The easiest way to load the .env file is using godotenv package. Open the terminal in the project root directory. go get github.com/joho/godotenv godotenv provides a Load method to load the env files. // Load the .env file in the current directorygodotenv.Load()// orgodotenv.Load(".env") Load method can load multiple env files at once. This also supports yaml. For more information check out the documentation. Create a new .env file in the project root directory. STRONGEST_AVENGER=Thor Update the main.go. package mainimport ( ... // Import godotenv "github.com/joho/godotenv")// use godot package to load/read the .env file and// return the value of the keyfunc goDotEnvVariable(key string) string { // load .env file err := godotenv.Load(".env") if err != nil { log.Fatalf("Error loading .env file") } return os.Getenv(key)}func main() { // os package ... // godotenv package dotenv := goDotEnvVariable("STRONGEST_AVENGER") fmt.Printf("godotenv : %s = %s \n", "STRONGEST_AVENGER", dotenv)} Open the terminal and run the main.go. go run main.go// Outputos package: name = gophergodotenv : STRONGEST_AVENGER = Thor Just add the code at the end of the os package in the main function. Viper is one of the most popular packages in the golang community. Many Go projects are built using Viper including Hugo, Docker Notary, Mercury. Viper 🐍 is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application and can handle all types of configuration needs and formats. Reading from JSON, TOML, YAML, HCL, envfile and Java properties config files For more information read the official documentation of viper Open the terminal in the project root directory. go get github.com/spf13/viper To set the config file and path viper.SetConfigFile(".env") To read the config file viper.ReadInConfig() To get the value from the config file using key viper.Get(key) Update the main.go. import ( "fmt" "log" "os" "github.com/joho/godotenv" "github.com/spf13/viper")// use viper package to read .env file// return the value of the keyfunc viperEnvVariable(key string) string { // SetConfigFile explicitly defines the path, name and extension of the config file. // Viper will use this and not check any of the config paths. // .env - It will search for the .env file in the current directory viper.SetConfigFile(".env") // Find and read the config file err := viper.ReadInConfig() if err != nil { log.Fatalf("Error while reading config file %s", err) } // viper.Get() returns an empty interface{} // to get the underlying type of the key, // we have to do the type assertion, we know the underlying value is string // if we type assert to other type it will throw an error value, ok := viper.Get(key).(string) // If the type is a string then ok will be true // ok will make sure the program not break if !ok { log.Fatalf("Invalid type assertion") } return value}func main() { // os package ... // godotenv package ... // viper package read .env viperenv := viperEnvVariable("STRONGEST_AVENGER") fmt.Printf("viper : %s = %s \n", "STRONGEST_AVENGER", viperenv)} Open the terminal and run the main.go. It supports: setting defaults reading from JSON, TOML, YAML, HCL, envfile and Java properties config files live watching and re-reading of config files (optional) reading from environment variables reading from remote config systems (etcd or Consul), and watching changes reading from command line flags reading from buffer setting explicit values Viper can be thought of as a registry for all of your applications configuration needs. Let’s experiment: 💣 Create a new config.yaml file in the project root directory. I_AM_INEVITABLE: "I am Iron Man" To set the config filename viper.SetConfigName("config") To set the config file path // Look in the current working directory viper.AddConfigPath(".") To read the config file viper.ReadInConfig() Update the main.go // use viper package to load/read the config file or .env file and// return the value of the keyfunc viperConfigVariable(key string) string { // name of config file (without extension) viper.SetConfigName("config") // look for config in the working directory viper.AddConfigPath(".") // Find and read the config file err := viper.ReadInConfig() if err != nil { log.Fatalf("Error while reading config file %s", err) } // viper.Get() returns an empty interface{} // to get the underlying type of the key, // we have to do the type assertion, we know the underlying value is string // if we type assert to other type it will throw an error value, ok := viper.Get(key).(string) // If the type is a string then ok will be true // ok will make sure the program not break if !ok { log.Fatalf("Invalid type assertion") } return value}func main() { // os package ... // godotenv package ... // viper package read .env ... // viper package read config file viperconfig := viperConfigVariable("I_AM_INEVITABLE") fmt.Printf("viper config : %s = %s \n", "I_AM_INEVITABLE", viperconfig) } Open the terminal and run the main.go go run main.go// Outputos package: name = gophergodotenv : STRONGEST_AVENGER = Thorviper : STRONGEST_AVENGER = Thorviper config : I_AM_INEVITABLE = I am Iron Man That’s it, now you can explore more of their secrets 🔐. If you find something worth sharing don’t hesitate 😉. The complete code is available in the GitHub.
[ { "code": null, "e": 293, "s": 172, "text": "When it comes to creating a production-grade application, using the environment variable in the application is de facto." }, { "code": null, "e": 323, "s": 293, "text": "Read my Latest articles here." }, { "code": null, "e": 517, "s": 323, "text": "Suppose you have an application with many features and each feature need to access the Database. You configured all the DB information like DBURL, DBNAME, USERNAME and PASSWORD in each feature." }, { "code": null, "e": 590, "s": 517, "text": "There are a few major disadvantages to this approach, there can be many." }, { "code": null, "e": 700, "s": 590, "text": "You’re entering all the information in the code. Now, all the unauthorized person also have access to the DB." }, { "code": null, "e": 813, "s": 700, "text": "If you’re using code versioning tool like git then the details of your DB will go public once you push the code." }, { "code": null, "e": 966, "s": 813, "text": "If you are changing a single variable then you have to change in all the features. There is a high possibility that you’ll miss one or two. 😌 been there" }, { "code": null, "e": 1083, "s": 966, "text": "You can categorize the environment variables like PROD, DEV, or TEST. Just prefix the variable with the environment." }, { "code": null, "e": 1181, "s": 1083, "text": "At the start, it might look like some extra work, but this will reward you a lot in your project." }, { "code": null, "e": 1255, "s": 1181, "text": "⚠️ Just don’t forget to include your environment files in the .gitignore." }, { "code": null, "e": 1285, "s": 1255, "text": "It is time for some action. 🔨" }, { "code": null, "e": 1361, "s": 1285, "text": "In this tutorial, we will access environment variables in 3 different ways." }, { "code": null, "e": 1404, "s": 1361, "text": "You can use according to your requirement." }, { "code": null, "e": 1415, "s": 1404, "text": "os package" }, { "code": null, "e": 1432, "s": 1415, "text": "godotenv package" }, { "code": null, "e": 1446, "s": 1432, "text": "viper package" }, { "code": null, "e": 1496, "s": 1446, "text": "Create a project go-env-ways outside the $GOPATH." }, { "code": null, "e": 1576, "s": 1496, "text": "Open the terminal inside the project root directory, and run the below command." }, { "code": null, "e": 1600, "s": 1576, "text": "go mod init go-env-ways" }, { "code": null, "e": 1731, "s": 1600, "text": "This module will keep a record of all the packages and their version used in the project. It is similar to package.json in nodejs." }, { "code": null, "e": 1783, "s": 1731, "text": "Let’s start with the easiest one, using os package." }, { "code": null, "e": 1873, "s": 1783, "text": "Golang provides os package, an easy way to configure and access the environment variable." }, { "code": null, "e": 1906, "s": 1873, "text": "To set the environment variable," }, { "code": null, "e": 1928, "s": 1906, "text": "os.Setenv(key, value)" }, { "code": null, "e": 1961, "s": 1928, "text": "To get the environment variable," }, { "code": null, "e": 1985, "s": 1961, "text": "value := os.Getenv(key)" }, { "code": null, "e": 2031, "s": 1985, "text": "Create a new file main.go inside the project." }, { "code": null, "e": 2461, "s": 2031, "text": "package mainimport ( \"fmt\" \"os\")// use os package to get the env variable which is already setfunc envVariable(key string) string { // set env variable using os package os.Setenv(key, \"gopher\") // return the env variable using os package return os.Getenv(key)}func main() { // os package value := envVariable(\"name\") fmt.Printf(\"os package: name = %s \\n\", value) fmt.Printf(\"environment = %s \\n\", os.Getenv(\"APP_ENV\"))}" }, { "code": null, "e": 2493, "s": 2461, "text": "Run the below command to check." }, { "code": null, "e": 2573, "s": 2493, "text": "APP_ENV=prod go run main.go// Outputos package: name = gopherenvironment = prod" }, { "code": null, "e": 2638, "s": 2573, "text": "The easiest way to load the .env file is using godotenv package." }, { "code": null, "e": 2687, "s": 2638, "text": "Open the terminal in the project root directory." }, { "code": null, "e": 2719, "s": 2687, "text": "go get github.com/joho/godotenv" }, { "code": null, "e": 2774, "s": 2719, "text": "godotenv provides a Load method to load the env files." }, { "code": null, "e": 2862, "s": 2774, "text": "// Load the .env file in the current directorygodotenv.Load()// orgodotenv.Load(\".env\")" }, { "code": null, "e": 2986, "s": 2862, "text": "Load method can load multiple env files at once. This also supports yaml. For more information check out the documentation." }, { "code": null, "e": 3040, "s": 2986, "text": "Create a new .env file in the project root directory." }, { "code": null, "e": 3063, "s": 3040, "text": "STRONGEST_AVENGER=Thor" }, { "code": null, "e": 3083, "s": 3063, "text": "Update the main.go." }, { "code": null, "e": 3594, "s": 3083, "text": "package mainimport ( ... // Import godotenv \"github.com/joho/godotenv\")// use godot package to load/read the .env file and// return the value of the keyfunc goDotEnvVariable(key string) string { // load .env file err := godotenv.Load(\".env\") if err != nil { log.Fatalf(\"Error loading .env file\") } return os.Getenv(key)}func main() { // os package ... // godotenv package dotenv := goDotEnvVariable(\"STRONGEST_AVENGER\") fmt.Printf(\"godotenv : %s = %s \\n\", \"STRONGEST_AVENGER\", dotenv)}" }, { "code": null, "e": 3633, "s": 3594, "text": "Open the terminal and run the main.go." }, { "code": null, "e": 3717, "s": 3633, "text": "go run main.go// Outputos package: name = gophergodotenv : STRONGEST_AVENGER = Thor" }, { "code": null, "e": 3786, "s": 3717, "text": "Just add the code at the end of the os package in the main function." }, { "code": null, "e": 3932, "s": 3786, "text": "Viper is one of the most popular packages in the golang community. Many Go projects are built using Viper including Hugo, Docker Notary, Mercury." }, { "code": null, "e": 4206, "s": 3932, "text": "Viper 🐍 is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application and can handle all types of configuration needs and formats. Reading from JSON, TOML, YAML, HCL, envfile and Java properties config files" }, { "code": null, "e": 4268, "s": 4206, "text": "For more information read the official documentation of viper" }, { "code": null, "e": 4317, "s": 4268, "text": "Open the terminal in the project root directory." }, { "code": null, "e": 4347, "s": 4317, "text": "go get github.com/spf13/viper" }, { "code": null, "e": 4379, "s": 4347, "text": "To set the config file and path" }, { "code": null, "e": 4407, "s": 4379, "text": "viper.SetConfigFile(\".env\")" }, { "code": null, "e": 4431, "s": 4407, "text": "To read the config file" }, { "code": null, "e": 4452, "s": 4431, "text": "viper.ReadInConfig()" }, { "code": null, "e": 4500, "s": 4452, "text": "To get the value from the config file using key" }, { "code": null, "e": 4515, "s": 4500, "text": "viper.Get(key)" }, { "code": null, "e": 4535, "s": 4515, "text": "Update the main.go." }, { "code": null, "e": 5751, "s": 4535, "text": "import ( \"fmt\" \"log\" \"os\" \"github.com/joho/godotenv\" \"github.com/spf13/viper\")// use viper package to read .env file// return the value of the keyfunc viperEnvVariable(key string) string { // SetConfigFile explicitly defines the path, name and extension of the config file. // Viper will use this and not check any of the config paths. // .env - It will search for the .env file in the current directory viper.SetConfigFile(\".env\") // Find and read the config file err := viper.ReadInConfig() if err != nil { log.Fatalf(\"Error while reading config file %s\", err) } // viper.Get() returns an empty interface{} // to get the underlying type of the key, // we have to do the type assertion, we know the underlying value is string // if we type assert to other type it will throw an error value, ok := viper.Get(key).(string) // If the type is a string then ok will be true // ok will make sure the program not break if !ok { log.Fatalf(\"Invalid type assertion\") } return value}func main() { // os package ... // godotenv package ... // viper package read .env viperenv := viperEnvVariable(\"STRONGEST_AVENGER\") fmt.Printf(\"viper : %s = %s \\n\", \"STRONGEST_AVENGER\", viperenv)}" }, { "code": null, "e": 5790, "s": 5751, "text": "Open the terminal and run the main.go." }, { "code": null, "e": 5803, "s": 5790, "text": "It supports:" }, { "code": null, "e": 5820, "s": 5803, "text": "setting defaults" }, { "code": null, "e": 5897, "s": 5820, "text": "reading from JSON, TOML, YAML, HCL, envfile and Java properties config files" }, { "code": null, "e": 5953, "s": 5897, "text": "live watching and re-reading of config files (optional)" }, { "code": null, "e": 5988, "s": 5953, "text": "reading from environment variables" }, { "code": null, "e": 6062, "s": 5988, "text": "reading from remote config systems (etcd or Consul), and watching changes" }, { "code": null, "e": 6094, "s": 6062, "text": "reading from command line flags" }, { "code": null, "e": 6114, "s": 6094, "text": "reading from buffer" }, { "code": null, "e": 6138, "s": 6114, "text": "setting explicit values" }, { "code": null, "e": 6226, "s": 6138, "text": "Viper can be thought of as a registry for all of your applications configuration needs." }, { "code": null, "e": 6246, "s": 6226, "text": "Let’s experiment: 💣" }, { "code": null, "e": 6307, "s": 6246, "text": "Create a new config.yaml file in the project root directory." }, { "code": null, "e": 6340, "s": 6307, "text": "I_AM_INEVITABLE: \"I am Iron Man\"" }, { "code": null, "e": 6367, "s": 6340, "text": "To set the config filename" }, { "code": null, "e": 6397, "s": 6367, "text": "viper.SetConfigName(\"config\")" }, { "code": null, "e": 6425, "s": 6397, "text": "To set the config file path" }, { "code": null, "e": 6491, "s": 6425, "text": "// Look in the current working directory viper.AddConfigPath(\".\")" }, { "code": null, "e": 6515, "s": 6491, "text": "To read the config file" }, { "code": null, "e": 6536, "s": 6515, "text": "viper.ReadInConfig()" }, { "code": null, "e": 6555, "s": 6536, "text": "Update the main.go" }, { "code": null, "e": 7668, "s": 6555, "text": "// use viper package to load/read the config file or .env file and// return the value of the keyfunc viperConfigVariable(key string) string { // name of config file (without extension) viper.SetConfigName(\"config\") // look for config in the working directory viper.AddConfigPath(\".\") // Find and read the config file err := viper.ReadInConfig() if err != nil { log.Fatalf(\"Error while reading config file %s\", err) } // viper.Get() returns an empty interface{} // to get the underlying type of the key, // we have to do the type assertion, we know the underlying value is string // if we type assert to other type it will throw an error value, ok := viper.Get(key).(string) // If the type is a string then ok will be true // ok will make sure the program not break if !ok { log.Fatalf(\"Invalid type assertion\") } return value}func main() { // os package ... // godotenv package ... // viper package read .env ... // viper package read config file viperconfig := viperConfigVariable(\"I_AM_INEVITABLE\") fmt.Printf(\"viper config : %s = %s \\n\", \"I_AM_INEVITABLE\", viperconfig) }" }, { "code": null, "e": 7706, "s": 7668, "text": "Open the terminal and run the main.go" }, { "code": null, "e": 7868, "s": 7706, "text": "go run main.go// Outputos package: name = gophergodotenv : STRONGEST_AVENGER = Thorviper : STRONGEST_AVENGER = Thorviper config : I_AM_INEVITABLE = I am Iron Man" }, { "code": null, "e": 7978, "s": 7868, "text": "That’s it, now you can explore more of their secrets 🔐. If you find something worth sharing don’t hesitate 😉." } ]
How to use Boto3 to start a crawler in AWS Glue Data Catalog
In this article, we will see how a user can start a crawler in AWS Glue Data Catalog. Problem Statement: Use boto3 library in Python to start a crawler. Step 1: Import boto3 and botocore exceptions to handle exceptions Step 1: Import boto3 and botocore exceptions to handle exceptions Step 2: crawler_name is the parameter in this function. Step 2: crawler_name is the parameter in this function. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 4: Create an AWS client for glue. Step 4: Create an AWS client for glue. Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name. Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name. Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException. Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException. Step 7: Handle the generic exception if something went wrong while starting a crawler. Step 7: Handle the generic exception if something went wrong while starting a crawler. The following code starts a crawler in AWS Glue Data Catalog − import boto3 from botocore.exceptions import ClientError def start_a_crawler(crawler_name) session = boto3.session.Session() glue_client = session.client('glue') try: response = glue_client.start_crawler(Name=crawler_name) return response except ClientError as e: raise Exception("boto3 client error in start_a_crawler: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in start_a_crawler: " + e.__str__()) #1st time start the crawler print(start_a_crawler("Data Dimension")) #2nd time run, before crawler completes the operation print(start_a_crawler("Data Dimension")) #1st time start the crawler {'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}} #2nd time run, before crawler completes the operation Exception: boto3 client error in start_a_crawler: An error occurred (CrawlerRunningException) when calling the StartCrawler operation: Crawler with name Data Dimension has already started
[ { "code": null, "e": 1148, "s": 1062, "text": "In this article, we will see how a user can start a crawler in AWS Glue Data Catalog." }, { "code": null, "e": 1215, "s": 1148, "text": "Problem Statement: Use boto3 library in Python to start a crawler." }, { "code": null, "e": 1281, "s": 1215, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions" }, { "code": null, "e": 1347, "s": 1281, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions" }, { "code": null, "e": 1403, "s": 1347, "text": "Step 2:\ncrawler_name is the parameter in this function." }, { "code": null, "e": 1459, "s": 1403, "text": "Step 2:\ncrawler_name is the parameter in this function." }, { "code": null, "e": 1654, "s": 1459, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 1849, "s": 1654, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 1888, "s": 1849, "text": "Step 4: Create an AWS client for glue." }, { "code": null, "e": 1927, "s": 1888, "text": "Step 4: Create an AWS client for glue." }, { "code": null, "e": 2015, "s": 1927, "text": "Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name." }, { "code": null, "e": 2103, "s": 2015, "text": "Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name." }, { "code": null, "e": 2274, "s": 2103, "text": "Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException." }, { "code": null, "e": 2445, "s": 2274, "text": "Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException." }, { "code": null, "e": 2532, "s": 2445, "text": "Step 7: Handle the generic exception if something went wrong while starting a crawler." }, { "code": null, "e": 2619, "s": 2532, "text": "Step 7: Handle the generic exception if something went wrong while starting a crawler." }, { "code": null, "e": 2682, "s": 2619, "text": "The following code starts a crawler in AWS Glue Data Catalog −" }, { "code": null, "e": 3318, "s": 2682, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef start_a_crawler(crawler_name)\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n response = glue_client.start_crawler(Name=crawler_name)\n return response\n except ClientError as e:\n raise Exception(\"boto3 client error in start_a_crawler: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in start_a_crawler: \" + e.__str__())\n\n#1st time start the crawler\nprint(start_a_crawler(\"Data Dimension\"))\n#2nd time run, before crawler completes the operation\nprint(start_a_crawler(\"Data Dimension\"))" }, { "code": null, "e": 3905, "s": 3318, "text": "#1st time start the crawler\n{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}\n\n#2nd time run, before crawler completes the operation\nException: boto3 client error in start_a_crawler: An error occurred (CrawlerRunningException) when calling the StartCrawler operation: Crawler with name Data Dimension has already started" } ]
How to resize an Entry Box by height in Tkinter?
An Entry widget in a Tkinter application supports singleline user inputs. You can configure the size of an Entry widget such as its width using the width property. However, tkinter has no height property to set the height of an Entry widget. To set the height, you can use the font('font_name', font-size) property. The font size of the text in an Entry widget always works as a height of the Entry widget. Let us take an example to understand this more clearly. Follow the steps given below − Import the required libraries Import the required libraries Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property. Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property. Create a Button to print the name of the user with the help of a Label widget. Create a Button to print the name of the user with the help of a Label widget. Define a function to create a Label to display the name of the users. Define a function to create a Label to display the name of the users. Use the get() function to return the string input from the Entry widget. Use the get() function to return the string input from the Entry widget. # Import the required libraries from tkinter import * # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Define a function def myClick(): greet= "Hello " + name.get() label=Label(win, text=greet, font=('Arial', 12)) label.pack(pady=10) # Create an entry widget name=Entry(win, width=50, font=('Arial 24')) name.pack(padx=10, pady=10) # Create a button button=Button(win, text="Submit", command=myClick) button.pack(pady=10) win.mainloop() Running the above program will display a window with an Entry widget asking users to enter their name and a Button to submit the name. When you hit "submit", it will display a Label widget on the screen. Now enter your name in the field and click "Submit" to see the output.
[ { "code": null, "e": 1469, "s": 1062, "text": "An Entry widget in a Tkinter application supports singleline user inputs. You can configure the size of an Entry widget such as its width using the width property. However, tkinter has no height property to set the height of an Entry widget. To set the height, you can use the font('font_name', font-size) property. The font size of the text in an Entry widget always works as a height of the Entry widget." }, { "code": null, "e": 1556, "s": 1469, "text": "Let us take an example to understand this more clearly. Follow the steps given below −" }, { "code": null, "e": 1586, "s": 1556, "text": "Import the required libraries" }, { "code": null, "e": 1616, "s": 1586, "text": "Import the required libraries" }, { "code": null, "e": 1722, "s": 1616, "text": "Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property." }, { "code": null, "e": 1828, "s": 1722, "text": "Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property." }, { "code": null, "e": 1907, "s": 1828, "text": "Create a Button to print the name of the user with the help of a Label widget." }, { "code": null, "e": 1986, "s": 1907, "text": "Create a Button to print the name of the user with the help of a Label widget." }, { "code": null, "e": 2056, "s": 1986, "text": "Define a function to create a Label to display the name of the users." }, { "code": null, "e": 2126, "s": 2056, "text": "Define a function to create a Label to display the name of the users." }, { "code": null, "e": 2199, "s": 2126, "text": "Use the get() function to return the string input from the Entry widget." }, { "code": null, "e": 2272, "s": 2199, "text": "Use the get() function to return the string input from the Entry widget." }, { "code": null, "e": 2787, "s": 2272, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a function\ndef myClick():\n greet= \"Hello \" + name.get()\n label=Label(win, text=greet, font=('Arial', 12))\n label.pack(pady=10)\n\n# Create an entry widget\nname=Entry(win, width=50, font=('Arial 24'))\nname.pack(padx=10, pady=10)\n\n# Create a button\nbutton=Button(win, text=\"Submit\", command=myClick)\nbutton.pack(pady=10)\n\nwin.mainloop()" }, { "code": null, "e": 2991, "s": 2787, "text": "Running the above program will display a window with an Entry widget asking users to enter their name and a Button to submit the name. When you hit \"submit\", it will display a Label widget on the screen." }, { "code": null, "e": 3062, "s": 2991, "text": "Now enter your name in the field and click \"Submit\" to see the output." } ]
Clean Up Data Noise with Fourier Transform in Python | by Andrew Zhu | Towards Data Science
Fourier Transform is a powerful way to view data from a completely different perspective: From the time-domain to the frequency-domain. But this powerful operation looks scary with its math equations. Transform time-domain wave to frequency-domain: The image below is a good one to illustrate the Fourier Transform: decomposite a complex wave into many regular sinusoids. Here is the complete animation explains what happens when transforming the time-domain wave data to frequency-domain view. We can easily manipulate data in the frequency domain, for example: removing noise waves. After that, we can use this inverse equation to transform the frequency-domain data back to time-domain wave: Let’s temporarily ignore the complexity of FT equations. Pretend that we have completely understood the meaning of the math equations and let’s go use Fourier Transform to do some real work in Python. The best way to understand anything is by using it, like the best way to learn swimming is getting wet by diving into the water. Create two sine waves and merge them into one sine wave, then purposefully contaminate the clean wave with data generated from np.random.randn(len(t)). import numpy as npimport matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = [16,10]plt.rcParams.update({'font.size':18})#Create a simple signal with two frequenciesdata_step = 0.001t = np.arange(start=0,stop=1,step=data_step)f_clean = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)f_noise = f_clean + 2.5*np.random.randn(len(t))plt.plot(t,f_noise,color='c',Linewidth=1.5,label='Noisy')plt.plot(t,f_clean,color='k',Linewidth=2,label='Clean')plt.legend() (Combining two signals to form a third signal is also called convolution or signal convolution. This is another interesting topic and nowadays intensively used in Neural Network Models) We have the waves with noise, black is the wave we want, green lines are noise. If I hide the colors in the chart, we can barely separate the noise out of the clean data. Fourier Transform can help here, all we need to do is transform the data to another perspective, from the time view(x-axis) to the frequency view(the x-axis will be the wave frequencies). You can use numpy.fft or scipy.fft. I found scipy.fft is pretty handy and fully functional. Here I will use scipy.fft in this article, but it is your choice if you want to use other modules, or you can even build one of your own(see the code later) based on the formula that I presented in the beginning. from scipy.fft import rfft,rfftfreqn = len(t)yf = rfft(f_noise)xf = rfftfreq(n,data_step)plt.plot(xf,np.abs(yf)) In the code, I use rfft instead of fft. the r means to reduce(I think) so that only positive frequencies will be computed. All negative mirrored frequencies will be omitted. and it is also faster. see more discussion here. The yf result from the rfft function is a complex number, in form like a+bj. the np.abs() function will calculate √(a2 + b2) for complex numbers. Here comes the magical Frequency-Domain view of our original waves. the x-axis represents frequencies. Something that looks complicated in the time-domain now is transformed to be very simple frequency-domain data. The two peaks represent the frequency of our two sine waves. One wave is 50Hz, another is 120Hz. Take another look back on the code that generates the sine waves. f_clean = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t) Other frequencies are noises, which will be easily removed in the next step. With help of Numpy, we can easily set those frequencies data as 0 except 50Hz and 120Hz. yf_abs = np.abs(yf) indices = yf_abs>300 # filter out those value under 300yf_clean = indices * yf # noise frequency will be set to 0plt.plot(xf,np.abs(yf_clean)) Now, all noises are removed. The code: from scipy.fft import irfftnew_f_clean = irfft(yf_clean)plt.plot(t,new_f_clean)plt.ylim(-6,8) As the result shows, all noise waves are removed. Back to the transform equation: The original time-domain signal is represented by lower case x. x[n] means the time-domain data point in the n position(time). The data point in frequency-domain is represented by upper case X. X[k] means the value at the frequency of k. Say, we have 10 data points. x = np.random.random(10) The N should be 10, so, the range of n is 0 to 9, 10 data points. The k represents the frequency #, its range is 0 to 9, why? the extreme condition will be each data point represent an independent sine wave. In a traditional programming language, it will need two for loops, one loop for k, another for the n. In Python, you can vectorize the operation with 0 explicit for loops (Expressive Python). And Python’s native support of complex numbers is awesome. let build the Fourier Transform function. import numpy as npfrom scipy.fft import fftdef DFT_slow(x): x = np.asarray(x, dtype=float)# ensure the data type N = x.shape[0] # get the x array length n = np.arange(N) # 1d array k = n.reshape((N, 1)) # 2d array, 10 x 1, aka column array M = np.exp(-2j * np.pi * k * n / N) return np.dot(M, x) # [a,b] . [c,d] = ac + bd, it is a sumx = np.random.random(1024)np.allclose(DFT_slow(x), fft(x)) This function is relatively slow compare with the one from numpy or scipy, but good enough for understanding how FFT function works. For faster implementation, read Jake’s Understanding the FFT Algorithm. The idea presented from Fourier Transform is so profound. It reminds me the world may not be what you see, the life you live on may have a completely different new face that can only be seen with a kind of transform, say Fourier Transform. You can not only transform the sound data, but also image, video, electromagnetic waves, or even stock trading data (Kondratiev wave). Fourier Transform can also be interpreted with wave generation circles. The big circle is our country, our era. We as an individual is the small tiny inner circle. Without the big circle that drives everything, we are really can’t do too much. The Industrial Revolution happened in England rather than in other countries not simply because of the adoption of steam engines, but so many other reasons. — Why England Industrialized First. it is the big circle that only exists in England at that time. If you are rich or very successful sometimes, somewhere, it is probably not all because of your own merit, but largely because of your country, people around you, or the good company you work with. Without those big circles that drive you forward, you may not able to achieve what you have now. The more I know about Fourier Transform, the more I am amazed by Joseph Fourier that he came up with this unbelievable equation in 1822. He could never know that his work is now used everywhere in the 21st century. All Fourier Transform mentioned in this article is referring to Discrete Fourier Transform. When you sit down in front of a computer and trying to do something with Fourier Transform, you will only use DFT - the Transform that is being discussed in this article. If you decide to sink your neck into the math swamp, here are two recommended books to read: Frequency Domain and Fourier Transforms. Paul W. Cuff’s textbook from Princeton. Frequency Domain and Fourier Transforms. Paul W. Cuff’s textbook from Princeton. 2. Chapter 8 of the book Digital Signal Processing — by Steven W.Smith they provided the online link: DSP Ch8 An Interactive Guide To The Fourier Transform: https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/Fourier Transforms With scipy.fft: Python Signal Processing:https://realpython.com/python-scipy-fft/Understanding the FFT Algorithm:http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/Frequency Domain and Fourier Transforms: https://www.princeton.edu/~cuff/ele201/kulkarni_text/frequency.pdfDenoising Data with FFT [Python]: https://www.youtube.com/watch?v=s2K1JfNR7Sc&ab_channel=SteveBruntonThe FFT Algorithm — Simple Step by Step: https://www.youtube.com/watch?v=htCj9exbGo0&ab_channel=SimonXu An Interactive Guide To The Fourier Transform: https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/ Fourier Transforms With scipy.fft: Python Signal Processing:https://realpython.com/python-scipy-fft/ Understanding the FFT Algorithm:http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/ Frequency Domain and Fourier Transforms: https://www.princeton.edu/~cuff/ele201/kulkarni_text/frequency.pdf Denoising Data with FFT [Python]: https://www.youtube.com/watch?v=s2K1JfNR7Sc&ab_channel=SteveBrunton The FFT Algorithm — Simple Step by Step: https://www.youtube.com/watch?v=htCj9exbGo0&ab_channel=SimonXu If you have any questions, leave a comment and I will do my best to answer, If you spot an error or mistake, don’t hesitate to mark them out. Your reading and support is the big circle that drives me to keep writing more. Thank You.
[ { "code": null, "e": 372, "s": 171, "text": "Fourier Transform is a powerful way to view data from a completely different perspective: From the time-domain to the frequency-domain. But this powerful operation looks scary with its math equations." }, { "code": null, "e": 420, "s": 372, "text": "Transform time-domain wave to frequency-domain:" }, { "code": null, "e": 543, "s": 420, "text": "The image below is a good one to illustrate the Fourier Transform: decomposite a complex wave into many regular sinusoids." }, { "code": null, "e": 666, "s": 543, "text": "Here is the complete animation explains what happens when transforming the time-domain wave data to frequency-domain view." }, { "code": null, "e": 866, "s": 666, "text": "We can easily manipulate data in the frequency domain, for example: removing noise waves. After that, we can use this inverse equation to transform the frequency-domain data back to time-domain wave:" }, { "code": null, "e": 1067, "s": 866, "text": "Let’s temporarily ignore the complexity of FT equations. Pretend that we have completely understood the meaning of the math equations and let’s go use Fourier Transform to do some real work in Python." }, { "code": null, "e": 1196, "s": 1067, "text": "The best way to understand anything is by using it, like the best way to learn swimming is getting wet by diving into the water." }, { "code": null, "e": 1348, "s": 1196, "text": "Create two sine waves and merge them into one sine wave, then purposefully contaminate the clean wave with data generated from np.random.randn(len(t))." }, { "code": null, "e": 1825, "s": 1348, "text": "import numpy as npimport matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = [16,10]plt.rcParams.update({'font.size':18})#Create a simple signal with two frequenciesdata_step = 0.001t = np.arange(start=0,stop=1,step=data_step)f_clean = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)f_noise = f_clean + 2.5*np.random.randn(len(t))plt.plot(t,f_noise,color='c',Linewidth=1.5,label='Noisy')plt.plot(t,f_clean,color='k',Linewidth=2,label='Clean')plt.legend()" }, { "code": null, "e": 2011, "s": 1825, "text": "(Combining two signals to form a third signal is also called convolution or signal convolution. This is another interesting topic and nowadays intensively used in Neural Network Models)" }, { "code": null, "e": 2091, "s": 2011, "text": "We have the waves with noise, black is the wave we want, green lines are noise." }, { "code": null, "e": 2370, "s": 2091, "text": "If I hide the colors in the chart, we can barely separate the noise out of the clean data. Fourier Transform can help here, all we need to do is transform the data to another perspective, from the time view(x-axis) to the frequency view(the x-axis will be the wave frequencies)." }, { "code": null, "e": 2675, "s": 2370, "text": "You can use numpy.fft or scipy.fft. I found scipy.fft is pretty handy and fully functional. Here I will use scipy.fft in this article, but it is your choice if you want to use other modules, or you can even build one of your own(see the code later) based on the formula that I presented in the beginning." }, { "code": null, "e": 2795, "s": 2675, "text": "from scipy.fft import rfft,rfftfreqn = len(t)yf = rfft(f_noise)xf = rfftfreq(n,data_step)plt.plot(xf,np.abs(yf))" }, { "code": null, "e": 3018, "s": 2795, "text": "In the code, I use rfft instead of fft. the r means to reduce(I think) so that only positive frequencies will be computed. All negative mirrored frequencies will be omitted. and it is also faster. see more discussion here." }, { "code": null, "e": 3164, "s": 3018, "text": "The yf result from the rfft function is a complex number, in form like a+bj. the np.abs() function will calculate √(a2 + b2) for complex numbers." }, { "code": null, "e": 3267, "s": 3164, "text": "Here comes the magical Frequency-Domain view of our original waves. the x-axis represents frequencies." }, { "code": null, "e": 3542, "s": 3267, "text": "Something that looks complicated in the time-domain now is transformed to be very simple frequency-domain data. The two peaks represent the frequency of our two sine waves. One wave is 50Hz, another is 120Hz. Take another look back on the code that generates the sine waves." }, { "code": null, "e": 3601, "s": 3542, "text": "f_clean = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)" }, { "code": null, "e": 3678, "s": 3601, "text": "Other frequencies are noises, which will be easily removed in the next step." }, { "code": null, "e": 3767, "s": 3678, "text": "With help of Numpy, we can easily set those frequencies data as 0 except 50Hz and 120Hz." }, { "code": null, "e": 3944, "s": 3767, "text": "yf_abs = np.abs(yf) indices = yf_abs>300 # filter out those value under 300yf_clean = indices * yf # noise frequency will be set to 0plt.plot(xf,np.abs(yf_clean))" }, { "code": null, "e": 3973, "s": 3944, "text": "Now, all noises are removed." }, { "code": null, "e": 3983, "s": 3973, "text": "The code:" }, { "code": null, "e": 4077, "s": 3983, "text": "from scipy.fft import irfftnew_f_clean = irfft(yf_clean)plt.plot(t,new_f_clean)plt.ylim(-6,8)" }, { "code": null, "e": 4127, "s": 4077, "text": "As the result shows, all noise waves are removed." }, { "code": null, "e": 4159, "s": 4127, "text": "Back to the transform equation:" }, { "code": null, "e": 4397, "s": 4159, "text": "The original time-domain signal is represented by lower case x. x[n] means the time-domain data point in the n position(time). The data point in frequency-domain is represented by upper case X. X[k] means the value at the frequency of k." }, { "code": null, "e": 4426, "s": 4397, "text": "Say, we have 10 data points." }, { "code": null, "e": 4451, "s": 4426, "text": "x = np.random.random(10)" }, { "code": null, "e": 4659, "s": 4451, "text": "The N should be 10, so, the range of n is 0 to 9, 10 data points. The k represents the frequency #, its range is 0 to 9, why? the extreme condition will be each data point represent an independent sine wave." }, { "code": null, "e": 4851, "s": 4659, "text": "In a traditional programming language, it will need two for loops, one loop for k, another for the n. In Python, you can vectorize the operation with 0 explicit for loops (Expressive Python)." }, { "code": null, "e": 4952, "s": 4851, "text": "And Python’s native support of complex numbers is awesome. let build the Fourier Transform function." }, { "code": null, "e": 5403, "s": 4952, "text": "import numpy as npfrom scipy.fft import fftdef DFT_slow(x): x = np.asarray(x, dtype=float)# ensure the data type N = x.shape[0] # get the x array length n = np.arange(N) # 1d array k = n.reshape((N, 1)) # 2d array, 10 x 1, aka column array M = np.exp(-2j * np.pi * k * n / N) return np.dot(M, x) # [a,b] . [c,d] = ac + bd, it is a sumx = np.random.random(1024)np.allclose(DFT_slow(x), fft(x))" }, { "code": null, "e": 5608, "s": 5403, "text": "This function is relatively slow compare with the one from numpy or scipy, but good enough for understanding how FFT function works. For faster implementation, read Jake’s Understanding the FFT Algorithm." }, { "code": null, "e": 5848, "s": 5608, "text": "The idea presented from Fourier Transform is so profound. It reminds me the world may not be what you see, the life you live on may have a completely different new face that can only be seen with a kind of transform, say Fourier Transform." }, { "code": null, "e": 5983, "s": 5848, "text": "You can not only transform the sound data, but also image, video, electromagnetic waves, or even stock trading data (Kondratiev wave)." }, { "code": null, "e": 6055, "s": 5983, "text": "Fourier Transform can also be interpreted with wave generation circles." }, { "code": null, "e": 6227, "s": 6055, "text": "The big circle is our country, our era. We as an individual is the small tiny inner circle. Without the big circle that drives everything, we are really can’t do too much." }, { "code": null, "e": 6483, "s": 6227, "text": "The Industrial Revolution happened in England rather than in other countries not simply because of the adoption of steam engines, but so many other reasons. — Why England Industrialized First. it is the big circle that only exists in England at that time." }, { "code": null, "e": 6778, "s": 6483, "text": "If you are rich or very successful sometimes, somewhere, it is probably not all because of your own merit, but largely because of your country, people around you, or the good company you work with. Without those big circles that drive you forward, you may not able to achieve what you have now." }, { "code": null, "e": 6993, "s": 6778, "text": "The more I know about Fourier Transform, the more I am amazed by Joseph Fourier that he came up with this unbelievable equation in 1822. He could never know that his work is now used everywhere in the 21st century." }, { "code": null, "e": 7085, "s": 6993, "text": "All Fourier Transform mentioned in this article is referring to Discrete Fourier Transform." }, { "code": null, "e": 7349, "s": 7085, "text": "When you sit down in front of a computer and trying to do something with Fourier Transform, you will only use DFT - the Transform that is being discussed in this article. If you decide to sink your neck into the math swamp, here are two recommended books to read:" }, { "code": null, "e": 7430, "s": 7349, "text": "Frequency Domain and Fourier Transforms. Paul W. Cuff’s textbook from Princeton." }, { "code": null, "e": 7511, "s": 7430, "text": "Frequency Domain and Fourier Transforms. Paul W. Cuff’s textbook from Princeton." }, { "code": null, "e": 7621, "s": 7511, "text": "2. Chapter 8 of the book Digital Signal Processing — by Steven W.Smith they provided the online link: DSP Ch8" }, { "code": null, "e": 8258, "s": 7621, "text": "An Interactive Guide To The Fourier Transform: https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/Fourier Transforms With scipy.fft: Python Signal Processing:https://realpython.com/python-scipy-fft/Understanding the FFT Algorithm:http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/Frequency Domain and Fourier Transforms: https://www.princeton.edu/~cuff/ele201/kulkarni_text/frequency.pdfDenoising Data with FFT [Python]: https://www.youtube.com/watch?v=s2K1JfNR7Sc&ab_channel=SteveBruntonThe FFT Algorithm — Simple Step by Step: https://www.youtube.com/watch?v=htCj9exbGo0&ab_channel=SimonXu" }, { "code": null, "e": 8389, "s": 8258, "text": "An Interactive Guide To The Fourier Transform: https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/" }, { "code": null, "e": 8490, "s": 8389, "text": "Fourier Transforms With scipy.fft: Python Signal Processing:https://realpython.com/python-scipy-fft/" }, { "code": null, "e": 8586, "s": 8490, "text": "Understanding the FFT Algorithm:http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/" }, { "code": null, "e": 8694, "s": 8586, "text": "Frequency Domain and Fourier Transforms: https://www.princeton.edu/~cuff/ele201/kulkarni_text/frequency.pdf" }, { "code": null, "e": 8796, "s": 8694, "text": "Denoising Data with FFT [Python]: https://www.youtube.com/watch?v=s2K1JfNR7Sc&ab_channel=SteveBrunton" }, { "code": null, "e": 8900, "s": 8796, "text": "The FFT Algorithm — Simple Step by Step: https://www.youtube.com/watch?v=htCj9exbGo0&ab_channel=SimonXu" } ]
Count the number of threads in a process on linux
Linux process can be visualized as a running instance of a program where each thread in the Linux is nothing but a flow of execution of the processes. Do you know how to see the number of threads per process on Linux environment? There are several ways to count the number of threads. This article deals with, how to read the information about processes on Linux and also to count the number of threads per process. To read the process information use ‘ps’ command. This command is used to read a snapshot of the current processes on Linux. However, ps -e or ps aux command displays the names of all processes. To read the process information, use the following command – $ ps The sample output should be like this – PID TTY TIME CMD 5843 pts/0 00:00:00 bash 5856 pts/0 00:00:00 ps To display all process names, use the following command – $ ps -e The sample output should be like this – PID TTY TIME CMD 1 ? 00:00:01 init 2 ? 00:00:00 kthreadd 3 ? 00:00:00 ksoftirqd/0 5 ? 00:00:00 kworker/0:0H 7 ? 00:00:07 rcu_sched 8 ? 00:00:00 rcu_bh 9 ? 00:00:02 rcuos/0 10 ? 00:00:00 rcuob/0 11 ? 00:00:00 migration/0 12 ? 00:00:00 watchdog/0 13 ? 00:00:00 watchdog/1 14 ? 00:00:00 migration/1 15 ? 00:00:00 ksoftirqd/1 17 ? 00:00:00 kworker/1:0H 18 ? 00:00:01 rcuos/1 19 ? 00:00:00 rcuob/1 20 ? 00:00:00 watchdog/2 21 ? 00:00:00 migration/2 22 ? 00:00:00 ksoftirqd/2 24 ? 00:00:00 kworker/2:0H 25 ? 00:00:04 rcuos/2 26 ? 00:00:00 rcuob/2 27 ? 00:00:00 watchdog/3 28 ? 00:00:00 migration/3 29 ? 00:00:00 ksoftirqd/3 31 ? 00:00:00 kworker/3:0H 32 ? 00:00:01 rcuos/3 33 ? 00:00:00 rcuob/3 34 ? 00:00:00 khelper 35 ? 00:00:00 kdevtmpfs 36 ? 00:00:00 netns 37 ? 00:00:00 perf 38 ? 00:00:00 khungtaskd 39 ? 00:00:00 writeback 40 ? 00:00:00 ksmd 41 ? 00:00:00 khugepaged 42 ? 00:00:00 crypto 43 ? 00:00:00 kintegrityd 44 ? 00:00:00 bioset 45 ? 00:00:00 kblockd 46 ? 00:00:00 ata_sff ............ There are several ways to count the threads per process. They are shown as below- This is the easiest way to see the thread count of any active process on a Linux machine. proc command exports text file of process and system hardware information, such as CPU, interrupts, memory, disk, etc. To see the thread count of process, use the following command- $ cat /proc/<pid>/status For example, here we are adding PID as 1041. Then, the command should be like this – $ cat /proc/1041/status The sample output should be like this- Name: cups-browsed State: S (sleeping) Tgid: 1041 Ngid: 0 Pid: 1041 PPid: 1 TracerPid: 0 Uid: 0 0 0 0 Gid: 0 0 0 0 FDSize: 64 Groups: 0 VmPeak: 75364 kB VmSize: 75364 kB VmLck: 0 kB VmPin: 0 kB VmHWM: 5932 kB VmRSS: 5932 kB VmData: 568 kB VmStk: 136 kB VmExe: 48 kB VmLib: 8712 kB VmPTE: 164 kB VmSwap: 0 kB Threads: 1 SigQ: 0/31329 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000001000 SigCgt: 0000000180004a02 CapInh: 0000000000000000 CapPrm: 0000003fffffffff CapEff: 0000003fffffffff CapBnd: 0000003fffffffff Seccomp: 0 Cpus_allowed: f Cpus_allowed_list: 0-3 Mems_allowed: 00000000,00000001 Mems_allowed_list: 0 voluntary_ctxt_switches: 134 nonvoluntary_ctxt_switches: 1 The above example is having one thread per process. An alternative way is to count the number of directories found in /proc/<pid>/task. Because, every thread which is created in a process, there will be a respective directory created in /proc/<pid>/task, named with its thread ID. Thus, the total number of directories in /proc/<pid>/ task represents the number of threads in the process. To verify it use the following command – $ ls /proc/<pid>/task | wc In the above command, we are giving PID as 1041, Then, the command should be like this – $ ls /proc/1041/task | wc The sample output should be like this- tp@linux:~$ ls /proc/1041/task |wc 1 1 5 The above output is describing about 1041 processes and it is having one directory in it. The ps command shows the individual threads with “H” option. The following command shows the thread count of the process. $ ps hH p 1041 | wc -l The output should be like this- tp@linux:~$ ps hH p 1041 | wc -l 1 tp@linux:~$ Congratulations! Now, you know “How to count the number of threads in a process on Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1478, "s": 1062, "text": "Linux process can be visualized as a running instance of a program where each thread in the Linux is nothing but a flow of execution of the processes. Do you know how to see the number of threads per process on Linux environment? There are several ways to count the number of threads. This article deals with, how to read the information about processes on Linux and also to count the number of threads per process." }, { "code": null, "e": 1673, "s": 1478, "text": "To read the process information use ‘ps’ command. This command is used to read a snapshot of the current processes on Linux. However, ps -e or ps aux command displays the names of all processes." }, { "code": null, "e": 1734, "s": 1673, "text": "To read the process information, use the following command –" }, { "code": null, "e": 1739, "s": 1734, "text": "$ ps" }, { "code": null, "e": 1779, "s": 1739, "text": "The sample output should be like this –" }, { "code": null, "e": 1844, "s": 1779, "text": "PID TTY TIME CMD\n5843 pts/0 00:00:00 bash\n5856 pts/0 00:00:00 ps" }, { "code": null, "e": 1902, "s": 1844, "text": "To display all process names, use the following command –" }, { "code": null, "e": 1910, "s": 1902, "text": "$ ps -e" }, { "code": null, "e": 1950, "s": 1910, "text": "The sample output should be like this –" }, { "code": null, "e": 3192, "s": 1950, "text": "PID TTY TIME CMD\n1 ? 00:00:01 init\n2 ? 00:00:00 kthreadd\n3 ? 00:00:00 ksoftirqd/0\n5 ? 00:00:00 kworker/0:0H\n7 ? 00:00:07 rcu_sched\n8 ? 00:00:00 rcu_bh\n9 ? 00:00:02 rcuos/0\n10 ? 00:00:00 rcuob/0\n11 ? 00:00:00 migration/0\n12 ? 00:00:00 watchdog/0\n13 ? 00:00:00 watchdog/1\n14 ? 00:00:00 migration/1\n15 ? 00:00:00 ksoftirqd/1\n17 ? 00:00:00 kworker/1:0H\n18 ? 00:00:01 rcuos/1\n19 ? 00:00:00 rcuob/1\n20 ? 00:00:00 watchdog/2\n21 ? 00:00:00 migration/2\n22 ? 00:00:00 ksoftirqd/2\n24 ? 00:00:00 kworker/2:0H\n25 ? 00:00:04 rcuos/2\n26 ? 00:00:00 rcuob/2\n27 ? 00:00:00 watchdog/3\n28 ? 00:00:00 migration/3\n29 ? 00:00:00 ksoftirqd/3\n31 ? 00:00:00 kworker/3:0H\n32 ? 00:00:01 rcuos/3\n33 ? 00:00:00 rcuob/3\n34 ? 00:00:00 khelper\n35 ? 00:00:00 kdevtmpfs\n36 ? 00:00:00 netns\n37 ? 00:00:00 perf\n38 ? 00:00:00 khungtaskd\n39 ? 00:00:00 writeback\n40 ? 00:00:00 ksmd\n41 ? 00:00:00 khugepaged\n42 ? 00:00:00 crypto\n43 ? 00:00:00 kintegrityd\n44 ? 00:00:00 bioset\n45 ? 00:00:00 kblockd\n46 ? 00:00:00 ata_sff\n............" }, { "code": null, "e": 3274, "s": 3192, "text": "There are several ways to count the threads per process. They are shown as below-" }, { "code": null, "e": 3483, "s": 3274, "text": "This is the easiest way to see the thread count of any active process on a Linux machine. proc command exports text file of process and system hardware information, such as CPU, interrupts, memory, disk, etc." }, { "code": null, "e": 3546, "s": 3483, "text": "To see the thread count of process, use the following command-" }, { "code": null, "e": 3571, "s": 3546, "text": "$ cat /proc/<pid>/status" }, { "code": null, "e": 3656, "s": 3571, "text": "For example, here we are adding PID as 1041. Then, the command should be like this –" }, { "code": null, "e": 3680, "s": 3656, "text": "$ cat /proc/1041/status" }, { "code": null, "e": 3719, "s": 3680, "text": "The sample output should be like this-" }, { "code": null, "e": 4439, "s": 3719, "text": "Name: cups-browsed\nState: S (sleeping)\nTgid: 1041\nNgid: 0\nPid: 1041\nPPid: 1\nTracerPid: 0\nUid: 0 0 0 0\nGid: 0 0 0 0\nFDSize: 64\nGroups: 0\nVmPeak: 75364 kB\nVmSize: 75364 kB\nVmLck: 0 kB\nVmPin: 0 kB\nVmHWM: 5932 kB\nVmRSS: 5932 kB\nVmData: 568 kB\nVmStk: 136 kB\nVmExe: 48 kB\nVmLib: 8712 kB\nVmPTE: 164 kB\nVmSwap: 0 kB\nThreads: 1\nSigQ: 0/31329\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: 0000000000000000\nSigIgn: 0000000000001000\nSigCgt: 0000000180004a02\nCapInh: 0000000000000000\nCapPrm: 0000003fffffffff\nCapEff: 0000003fffffffff\nCapBnd: 0000003fffffffff\nSeccomp: 0\nCpus_allowed: f\nCpus_allowed_list: 0-3\nMems_allowed: 00000000,00000001\nMems_allowed_list: 0\nvoluntary_ctxt_switches: 134\nnonvoluntary_ctxt_switches: 1" }, { "code": null, "e": 4575, "s": 4439, "text": "The above example is having one thread per process. An alternative way is to count the number of directories found in /proc/<pid>/task." }, { "code": null, "e": 4828, "s": 4575, "text": "Because, every thread which is created in a process, there will be a respective directory created in /proc/<pid>/task, named with its thread ID. Thus, the total number of directories in /proc/<pid>/ task represents the number of threads in the process." }, { "code": null, "e": 4869, "s": 4828, "text": "To verify it use the following command –" }, { "code": null, "e": 4896, "s": 4869, "text": "$ ls /proc/<pid>/task | wc" }, { "code": null, "e": 4985, "s": 4896, "text": "In the above command, we are giving PID as 1041, Then, the command should be like this –" }, { "code": null, "e": 5011, "s": 4985, "text": "$ ls /proc/1041/task | wc" }, { "code": null, "e": 5050, "s": 5011, "text": "The sample output should be like this-" }, { "code": null, "e": 5091, "s": 5050, "text": "tp@linux:~$ ls /proc/1041/task |wc\n1 1 5" }, { "code": null, "e": 5181, "s": 5091, "text": "The above output is describing about 1041 processes and it is having one directory in it." }, { "code": null, "e": 5303, "s": 5181, "text": "The ps command shows the individual threads with “H” option. The following command shows the thread count of the process." }, { "code": null, "e": 5326, "s": 5303, "text": "$ ps hH p 1041 | wc -l" }, { "code": null, "e": 5358, "s": 5326, "text": "The output should be like this-" }, { "code": null, "e": 5405, "s": 5358, "text": "tp@linux:~$ ps hH p 1041 | wc -l\n1\ntp@linux:~$" }, { "code": null, "e": 5581, "s": 5405, "text": "Congratulations! Now, you know “How to count the number of threads in a process on Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Count total set bits in all numbers from 1 to n | Set 2 - GeeksforGeeks
18 Nov, 2021 Given a positive integer N, the task is to count the sum of the number of set bits in the binary representation of all the numbers from 1 to N.Examples: Input: N = 3 Output: 4 1 + 1 + 2 = 4Input: N = 16 Output: 33 Approach: Some other approaches to solve this problem has been discussed here. In this article, another approach with time complexity O(logN) has been discussed. Check the pattern of Binary representation of the numbers from 1 to N in the following table: Notice that, Every alternate bits in A are set.Every 2 alternate bits in B are set.Every 4 alternate bits in C are set.Every 8 alternate bits in D are set......This will keep on repeating for every power of 2. Every alternate bits in A are set. Every 2 alternate bits in B are set. Every 4 alternate bits in C are set. Every 8 alternate bits in D are set. ..... This will keep on repeating for every power of 2. So, we will iterate till the number of bits in the number. And we don’t have to iterate every single number in the range from 1 to n. We will perform the following operations to get the desired result. , First of all, we will add 1 to the number in order to compensate 0. As the binary number system starts from 0. So now n = n + 1. We will keep the track of the number of set bits encountered till now. And we will initialise it with n/2. We will keep one variable which is a power of 2, in order to keep track of bit we are computing. We will iterate till the power of 2 becomes greater than n. We can get the number of pairs of 0s and 1s in the current bit for all the numbers by dividing n by current power of 2. Now we have to add the bits in the set bits count. We can do this by dividing the number of pairs of 0s and 1s by 2 which will give us the number of pairs of 1s only and after that, we will multiply that with the current power of 2 to get the count of ones in the groups. Now there may be a chance that we get a number as number of pairs, which is somewhere in the middle of the group i.e. the number of 1s are less than the current power of 2 in that particular group. So, we will find modulus and add that to the count of set bits which will be clear with the help of an example. Example: Consider N = 14 From the table above, there will be 28 set bits in total from 1 to 14. We will be considering 20 as A, 21 as B, 22 as C and 23 as DFirst of all we will add 1 to number N, So now our N = 14 + 1 = 15. ^ represents raise to the power ,not XOR. eg. 2^3 means 2 raise to 3. Calculation for A (20 = 1) 15/2 = 7 Number of set bits in A = 7 ————> (i) Calculation for B (2^1 = 2) 15/2 = 7 => there are 7 groups of 0s and 1s Now, to compute number of groups of set bits only, we have to divide that by 2. So, 7/2 = 3. There are 3 set bit groups. And these groups will contain set bits equal to power of 2 this time, which is 2. So we will multiply number of set bit groups with power of 2 => 3*2 = 6 —>(2i) Plus There may be some extra 1s in this because 4th group is not considered, as this division will give us only integer value. So we have to add that as well. Note: – This will happen only when number of groups of 0s and 1s is odd. 15%2 = 1 —>(2ii) 2i + 2ii => 6 + 1 = 7 ————>(ii) Calculation for C (2^2 = 4) 15/4 = 3 => there are 3 groups of 0s and 1s Number of set bit groups = 3/2 = 1 Number of set bits in those groups = 1*4 = 4 —> (3i) As 3 is odd, we have to add bits in the group which is not considered So, 15%4 = 3 —> (3ii) 3i + 3ii = 4 + 3 = 7 ————>(iii) Calculation for D (2^3 = 8) 15/8 = 1 => there is 1 group of 0s and 1s. Now in this case there is only one group and that too of only 0. Number of set bit groups = 1/2 = 0 Number of set bits in those groups = 0 * 8 = 0 —> (4i) As number of groups are odd, So, 15%8 = 7 —> (4ii) 4i + 4ii = 0 + 7 = 7 ————>(iv) At this point, our power of 2 variable becomes greater than the number, which is 15 in our case. (power of 2 = 16 and 16 > 15). So the loop gets terminated here. Final output = i + ii + iii + iv = 7 + 7 + 7 + 7 = 28 Number of set bits from 1 to 14 are 28.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to return the sum of the count// of set bits in the integers from 1 to nint countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs & 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codeint main(){ int n = 14; cout << countSetBits(n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the sum of the count// of set bits in the integers from 1 to nstatic int countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codepublic static void main(String[] args){ int n = 14; System.out.println(countSetBits(n));}} // This code is contributed by Princi Singh # Python3 implementation of the approach # Function to return the sum of the count# of set bits in the integers from 1 to ndef countSetBits(n) : # Ignore 0 as all the bits are unset n += 1; # To store the powers of 2 powerOf2 = 2; # To store the result, it is initialized # with n/2 because the count of set # least significant bits in the integers # from 1 to n is n/2 cnt = n // 2; # Loop for every bit required to represent n while (powerOf2 <= n) : # Total count of pairs of 0s and 1s totalPairs = n // powerOf2; # totalPairs/2 gives the complete # count of the pairs of 1s # Multiplying it with the current power # of 2 will give the count of # 1s in the current bit cnt += (totalPairs // 2) * powerOf2; # If the count of pairs was odd then # add the remaining 1s which could # not be groupped together if (totalPairs & 1) : cnt += (n % powerOf2) else : cnt += 0 # Next power of 2 powerOf2 <<= 1; # Return the result return cnt; # Driver codeif __name__ == "__main__" : n = 14; print(countSetBits(n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the sum of the count// of set bits in the integers from 1 to nstatic int countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codepublic static void Main(String[] args){ int n = 14; Console.WriteLine(countSetBits(n));}} // This code is contributed by 29AjayKumar <script>// javascript implementation of the approach// Function to return the sum of the count// of set bits in the integers from 1 to nfunction countSetBits(n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 var powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 var cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s var totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codevar n = 14; document.write(countSetBits(n)); // This code is contributed by 29AjayKumar</script> 28 Time Complexity: O(log n) Auxiliary Space: O(1) ankthon princi singh 29AjayKumar mewtwo28 subhammahato348 Numbers setBitCount Bit Magic Mathematical Mathematical Bit Magic Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Find the element that appears once Bits manipulation (Important tactics) Set, Clear and Toggle a given bit of a number in C Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24909, "s": 24881, "text": "\n18 Nov, 2021" }, { "code": null, "e": 25064, "s": 24909, "text": "Given a positive integer N, the task is to count the sum of the number of set bits in the binary representation of all the numbers from 1 to N.Examples: " }, { "code": null, "e": 25089, "s": 25064, "text": "Input: N = 3 Output: 4 " }, { "code": null, "e": 25129, "s": 25089, "text": "1 + 1 + 2 = 4Input: N = 16 Output: 33 " }, { "code": null, "e": 25389, "s": 25131, "text": "Approach: Some other approaches to solve this problem has been discussed here. In this article, another approach with time complexity O(logN) has been discussed. Check the pattern of Binary representation of the numbers from 1 to N in the following table: " }, { "code": null, "e": 25404, "s": 25389, "text": "Notice that, " }, { "code": null, "e": 25601, "s": 25404, "text": "Every alternate bits in A are set.Every 2 alternate bits in B are set.Every 4 alternate bits in C are set.Every 8 alternate bits in D are set......This will keep on repeating for every power of 2." }, { "code": null, "e": 25636, "s": 25601, "text": "Every alternate bits in A are set." }, { "code": null, "e": 25673, "s": 25636, "text": "Every 2 alternate bits in B are set." }, { "code": null, "e": 25710, "s": 25673, "text": "Every 4 alternate bits in C are set." }, { "code": null, "e": 25747, "s": 25710, "text": "Every 8 alternate bits in D are set." }, { "code": null, "e": 25753, "s": 25747, "text": "....." }, { "code": null, "e": 25803, "s": 25753, "text": "This will keep on repeating for every power of 2." }, { "code": null, "e": 26007, "s": 25803, "text": "So, we will iterate till the number of bits in the number. And we don’t have to iterate every single number in the range from 1 to n. We will perform the following operations to get the desired result. " }, { "code": null, "e": 26138, "s": 26007, "text": ", First of all, we will add 1 to the number in order to compensate 0. As the binary number system starts from 0. So now n = n + 1." }, { "code": null, "e": 26245, "s": 26138, "text": "We will keep the track of the number of set bits encountered till now. And we will initialise it with n/2." }, { "code": null, "e": 26342, "s": 26245, "text": "We will keep one variable which is a power of 2, in order to keep track of bit we are computing." }, { "code": null, "e": 26402, "s": 26342, "text": "We will iterate till the power of 2 becomes greater than n." }, { "code": null, "e": 26522, "s": 26402, "text": "We can get the number of pairs of 0s and 1s in the current bit for all the numbers by dividing n by current power of 2." }, { "code": null, "e": 26794, "s": 26522, "text": "Now we have to add the bits in the set bits count. We can do this by dividing the number of pairs of 0s and 1s by 2 which will give us the number of pairs of 1s only and after that, we will multiply that with the current power of 2 to get the count of ones in the groups." }, { "code": null, "e": 27104, "s": 26794, "text": "Now there may be a chance that we get a number as number of pairs, which is somewhere in the middle of the group i.e. the number of 1s are less than the current power of 2 in that particular group. So, we will find modulus and add that to the count of set bits which will be clear with the help of an example." }, { "code": null, "e": 27371, "s": 27104, "text": "Example: Consider N = 14 From the table above, there will be 28 set bits in total from 1 to 14. We will be considering 20 as A, 21 as B, 22 as C and 23 as DFirst of all we will add 1 to number N, So now our N = 14 + 1 = 15. ^ represents raise to the power ,not XOR." }, { "code": null, "e": 27399, "s": 27371, "text": "eg. 2^3 means 2 raise to 3." }, { "code": null, "e": 27473, "s": 27399, "text": "Calculation for A (20 = 1) 15/2 = 7 Number of set bits in A = 7 ————> (i)" }, { "code": null, "e": 28108, "s": 27473, "text": "Calculation for B (2^1 = 2) 15/2 = 7 => there are 7 groups of 0s and 1s Now, to compute number of groups of set bits only, we have to divide that by 2. So, 7/2 = 3. There are 3 set bit groups. And these groups will contain set bits equal to power of 2 this time, which is 2. So we will multiply number of set bit groups with power of 2 => 3*2 = 6 —>(2i) Plus There may be some extra 1s in this because 4th group is not considered, as this division will give us only integer value. So we have to add that as well. Note: – This will happen only when number of groups of 0s and 1s is odd. 15%2 = 1 —>(2ii) 2i + 2ii => 6 + 1 = 7 ————>(ii)" }, { "code": null, "e": 28392, "s": 28108, "text": "Calculation for C (2^2 = 4) 15/4 = 3 => there are 3 groups of 0s and 1s Number of set bit groups = 3/2 = 1 Number of set bits in those groups = 1*4 = 4 —> (3i) As 3 is odd, we have to add bits in the group which is not considered So, 15%4 = 3 —> (3ii) 3i + 3ii = 4 + 3 = 7 ————>(iii)" }, { "code": null, "e": 28700, "s": 28392, "text": "Calculation for D (2^3 = 8) 15/8 = 1 => there is 1 group of 0s and 1s. Now in this case there is only one group and that too of only 0. Number of set bit groups = 1/2 = 0 Number of set bits in those groups = 0 * 8 = 0 —> (4i) As number of groups are odd, So, 15%8 = 7 —> (4ii) 4i + 4ii = 0 + 7 = 7 ————>(iv)" }, { "code": null, "e": 29008, "s": 28700, "text": "At this point, our power of 2 variable becomes greater than the number, which is 15 in our case. (power of 2 = 16 and 16 > 15). So the loop gets terminated here. Final output = i + ii + iii + iv = 7 + 7 + 7 + 7 = 28 Number of set bits from 1 to 14 are 28.Below is the implementation of the above approach: " }, { "code": null, "e": 29012, "s": 29008, "text": "C++" }, { "code": null, "e": 29017, "s": 29012, "text": "Java" }, { "code": null, "e": 29025, "s": 29017, "text": "Python3" }, { "code": null, "e": 29028, "s": 29025, "text": "C#" }, { "code": null, "e": 29039, "s": 29028, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the sum of the count// of set bits in the integers from 1 to nint countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs & 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codeint main(){ int n = 14; cout << countSetBits(n); return 0;}", "e": 30261, "s": 29039, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the sum of the count// of set bits in the integers from 1 to nstatic int countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codepublic static void main(String[] args){ int n = 14; System.out.println(countSetBits(n));}} // This code is contributed by Princi Singh", "e": 31562, "s": 30261, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the sum of the count# of set bits in the integers from 1 to ndef countSetBits(n) : # Ignore 0 as all the bits are unset n += 1; # To store the powers of 2 powerOf2 = 2; # To store the result, it is initialized # with n/2 because the count of set # least significant bits in the integers # from 1 to n is n/2 cnt = n // 2; # Loop for every bit required to represent n while (powerOf2 <= n) : # Total count of pairs of 0s and 1s totalPairs = n // powerOf2; # totalPairs/2 gives the complete # count of the pairs of 1s # Multiplying it with the current power # of 2 will give the count of # 1s in the current bit cnt += (totalPairs // 2) * powerOf2; # If the count of pairs was odd then # add the remaining 1s which could # not be groupped together if (totalPairs & 1) : cnt += (n % powerOf2) else : cnt += 0 # Next power of 2 powerOf2 <<= 1; # Return the result return cnt; # Driver codeif __name__ == \"__main__\" : n = 14; print(countSetBits(n)); # This code is contributed by AnkitRai01", "e": 32793, "s": 31562, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum of the count// of set bits in the integers from 1 to nstatic int countSetBits(int n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 int powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 int cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s int totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codepublic static void Main(String[] args){ int n = 14; Console.WriteLine(countSetBits(n));}} // This code is contributed by 29AjayKumar", "e": 34108, "s": 32793, "text": null }, { "code": "<script>// javascript implementation of the approach// Function to return the sum of the count// of set bits in the integers from 1 to nfunction countSetBits(n){ // Ignore 0 as all the bits are unset n++; // To store the powers of 2 var powerOf2 = 2; // To store the result, it is initialized // with n/2 because the count of set // least significant bits in the integers // from 1 to n is n/2 var cnt = n / 2; // Loop for every bit required to represent n while (powerOf2 <= n) { // Total count of pairs of 0s and 1s var totalPairs = n / powerOf2; // totalPairs/2 gives the complete // count of the pairs of 1s // Multiplying it with the current power // of 2 will give the count of // 1s in the current bit cnt += (totalPairs / 2) * powerOf2; // If the count of pairs was odd then // add the remaining 1s which could // not be groupped together cnt += (totalPairs % 2 == 1) ? (n % powerOf2) : 0; // Next power of 2 powerOf2 <<= 1; } // Return the result return cnt;} // Driver codevar n = 14; document.write(countSetBits(n)); // This code is contributed by 29AjayKumar</script>", "e": 35361, "s": 34108, "text": null }, { "code": null, "e": 35364, "s": 35361, "text": "28" }, { "code": null, "e": 35392, "s": 35366, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 35414, "s": 35392, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 35422, "s": 35414, "text": "ankthon" }, { "code": null, "e": 35435, "s": 35422, "text": "princi singh" }, { "code": null, "e": 35447, "s": 35435, "text": "29AjayKumar" }, { "code": null, "e": 35456, "s": 35447, "text": "mewtwo28" }, { "code": null, "e": 35472, "s": 35456, "text": "subhammahato348" }, { "code": null, "e": 35480, "s": 35472, "text": "Numbers" }, { "code": null, "e": 35492, "s": 35480, "text": "setBitCount" }, { "code": null, "e": 35502, "s": 35492, "text": "Bit Magic" }, { "code": null, "e": 35515, "s": 35502, "text": "Mathematical" }, { "code": null, "e": 35528, "s": 35515, "text": "Mathematical" }, { "code": null, "e": 35538, "s": 35528, "text": "Bit Magic" }, { "code": null, "e": 35546, "s": 35538, "text": "Numbers" }, { "code": null, "e": 35644, "s": 35546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35653, "s": 35644, "text": "Comments" }, { "code": null, "e": 35666, "s": 35653, "text": "Old Comments" }, { "code": null, "e": 35712, "s": 35666, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 35763, "s": 35712, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 35798, "s": 35763, "text": "Find the element that appears once" }, { "code": null, "e": 35836, "s": 35798, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 35887, "s": 35836, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 35917, "s": 35887, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35977, "s": 35917, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35992, "s": 35977, "text": "C++ Data Types" }, { "code": null, "e": 36035, "s": 35992, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Create a Random Graph Using Random Edge Generation in Java? - GeeksforGeeks
08 Dec, 2020 We know that Graph is a data structure that consists of a finite set of vertices and edges(that connect the vertices with each other). A graph can be directed(edges having a direction) or undirected(edges with no directions). However, a Random graph is a graph data structure that is generated randomly. Random Graph models are widely used in studying complex networks, social networks, communication engineering and even in biology(in studying intracellular regulatory networks, activating and inhibiting connections in biological networks etc.). In this article, we are going to discuss some algorithms to generate various types of random graphs. Algorithm 1: This algorithm is based on randomly choosing the number of vertices and edges and then randomly selecting two vertices to add an edge between them. Randomly choose the number of vertices and edges. Say, V be the number of vertices and E be the number of edgesCheck if the chosen number of edges E is compatible with the number of vertices. As for a chosen number of vertices V, there can be at-most (V*(V-1)/2) edges (Why V*(V – 1)/2 ? it is discussed later) in an undirected graph(if it does not contain self-loops).Run a for loop that runs for i = 0 to i < number of edges E, and during each iteration, randomly choose two vertices and create an edge between them.Print the created graph. Randomly choose the number of vertices and edges. Say, V be the number of vertices and E be the number of edges Check if the chosen number of edges E is compatible with the number of vertices. As for a chosen number of vertices V, there can be at-most (V*(V-1)/2) edges (Why V*(V – 1)/2 ? it is discussed later) in an undirected graph(if it does not contain self-loops). Run a for loop that runs for i = 0 to i < number of edges E, and during each iteration, randomly choose two vertices and create an edge between them. Print the created graph. Below is the implementation of the above approach: Java // Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for // the number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // add an edge between them addEdge(v, w); } } // Method to compute the maximum number of possible // edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is an undirected graph // So, for a given number of vertices // there can be at-most v*(v-1)/2 number of edges return numOfVertices * ((numOfVertices - 1) / 2); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is an Undirected graph // Add w to v's adjacency list adjacencyList.get(v).add(w); // Add v to w's adjacency list adjacencyList.get(w).add(v); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println("The generated random graph :"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + " -> { "); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(" No adjacent vertices "); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(" , "); } } System.out.println("}"); } }} The generated random graph : 0 -> { 7 , 10 , 7 , 2 , 8 , 7 , 1} 1 -> { 5 , 8 , 8 , 3 , 4 , 12 , 8 , 7 , 9 , 0 , 7} 2 -> { 2 , 2 , 7 , 0 , 2 , 2 , 11 , 12 , 3 , 9 , 4 , 2 , 2 , 12 , 5} 3 -> { 6 , 10 , 1 , 12 , 11 , 2 , 10 , 10 , 3 , 3 , 5} 4 -> { 1 , 8 , 6 , 8 , 8 , 2 , 5 , 11} 5 -> { 1 , 5 , 5 , 8 , 4 , 2 , 11 , 3} 6 -> { 3 , 9 , 12 , 4 , 10 , 8 , 9} 7 -> { 0 , 2 , 0 , 12 , 1 , 7 , 7 , 12 , 0 , 8 , 1} 8 -> { 5 , 1 , 1 , 0 , 1 , 4 , 4 , 4 , 6 , 11 , 7} 9 -> { 6 , 12 , 1 , 2 , 9 , 9 , 6 , 9 , 9} 10 -> { 3 , 0 , 3 , 3 , 10 , 10 , 6} 11 -> { 3 , 2 , 12 , 8 , 4 , 5} 12 -> { 7 , 3 , 9 , 1 , 6 , 11 , 2 , 7 , 2} Each time you run the above program you will get a different undirected graph. 2. Remove the repetitions of the edges Check if the edge already exists or not at run time. Using this approach complexity of the algorithm 1 will get increase but the optimization in the memory increases. Below is the implementation of the above approach: Java // Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the number // of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list representation // for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // Check if there is already // an edge between v and w if (adjacencyList.get(v).contains(w)) { // Reduce the value of i // so that again v and w can be chosen // for the same edge count i = i - 1; continue; } // Add an edge between them if // not previously created addEdge(v, w); } } // Method to compute the maximum number of possible // edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is an undirected graph // So, for a given number of vertices V // there can be at-most V*(V-1)/2 number of edges return numOfVertices * ((numOfVertices - 1) / 2); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is an Undirected graph // Add w to v's adjacency list adjacencyList.get(v).add(w); // Add v to w's adjacency list // if v is not equal to w if (v != w) adjacencyList.get(w).add(v); // The above condition is important // If you don't apply the condition then // two self-loops will be created if // v and w are equal } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println("The generated random graph :"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + " -> { "); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(" No adjacent vertices "); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(" , "); } } System.out.println("}"); } }} The generated random graph : 0 -> { 7 , 0 , 9 , 16 , 8 , 3 , 14 , 17 , 10 , 1 , 6 , 11 , 5 , 4 , 12} 1 -> { 17 , 8 , 6 , 12 , 9 , 11 , 13 , 5 , 15 , 0 , 2 , 7 , 16 , 3} 2 -> { 11 , 16 , 9 , 8 , 6 , 13 , 17 , 4 , 2 , 14 , 1 , 7 , 10} 3 -> { 4 , 8 , 13 , 10 , 12 , 17 , 0 , 15 , 16 , 3 , 7 , 6 , 5 , 1} 4 -> { 3 , 17 , 5 , 15 , 16 , 8 , 2 , 7 , 13 , 6 , 9 , 4 , 11 , 14 , 12 , 0} 5 -> { 10 , 17 , 6 , 16 , 4 , 9 , 14 , 13 , 8 , 1 , 3 , 5 , 0 , 15 , 7} 6 -> { 5 , 2 , 8 , 1 , 15 , 16 , 12 , 14 , 4 , 6 , 3 , 0 , 17 , 10 , 7} 7 -> { 9 , 11 , 0 , 15 , 7 , 4 , 10 , 13 , 17 , 16 , 3 , 8 , 1 , 6 , 2 , 5 , 12} 8 -> { 16 , 3 , 2 , 1 , 17 , 6 , 13 , 0 , 15 , 4 , 14 , 5 , 7 , 12 , 9 , 11} 9 -> { 7 , 10 , 2 , 9 , 0 , 1 , 5 , 17 , 16 , 4 , 12 , 11 , 13 , 8} 10 -> { 11 , 5 , 9 , 3 , 12 , 7 , 13 , 10 , 16 , 14 , 17 , 0 , 15 , 6 , 2} 11 -> { 2 , 10 , 17 , 12 , 7 , 15 , 16 , 11 , 1 , 13 , 14 , 4 , 9 , 0 , 8} 12 -> { 12 , 11 , 3 , 1 , 6 , 10 , 16 , 15 , 8 , 9 , 4 , 13 , 0 , 7} 13 -> { 14 , 3 , 17 , 15 , 2 , 8 , 7 , 10 , 5 , 1 , 4 , 11 , 9 , 13 , 12} 14 -> { 13 , 5 , 2 , 8 , 6 , 0 , 10 , 11 , 4 , 17 , 15} 15 -> { 13 , 11 , 17 , 4 , 7 , 6 , 8 , 3 , 1 , 12 , 10 , 16 , 14 , 5} 16 -> { 2 , 8 , 5 , 0 , 4 , 6 , 11 , 12 , 9 , 3 , 10 , 7 , 17 , 15 , 1} 17 -> { 1 , 11 , 5 , 4 , 13 , 8 , 15 , 3 , 2 , 9 , 7 , 0 , 16 , 10 , 14 , 6} Now the output undirected graph does not contain any multiple edges between the same vertices. Though the graph may contain self-loops(but now only one for each vertex). However, if you want to generate undirected graphs without self-loops, then you can add another condition to the above code //Check if there is already an edge between v and w or v and w are equal if((v == w ) || adjacencyList.get(v).contains(w)) { //Reduce the value of i //so that again v and w can be chosen //for the same edge count i = i - 1; continue; } Now, no self-loops and multiple edges are allowed in the generated undirected graph. Why for a given number of vertices V in an undirected graph, there can be at-most V*((V-1)/2) number of edges? Suppose, there are V number of vertices in a directed graph. Now, if the graph doesn’t contain any self-loops and multiple edges, then each vertex can have (V-1) edges with other (V-1) vertices. So, V vertices can have at-most V*(V – 1) vertices. If the graph contains self-loops then the maximum possible number of edges is V2 (with no multiple edges). Because, each vertex can have an edge with itself also. So, for Undirected graphs, the maximum possible number of edges is V*(V – 1)/2 as the edges don’t have any directions. Till now, we have created random undirected graphs, however, if you want to create random directed graphs, then we have to make some changes to the above implemented code — For a randomly chosen number of vertices V, the maximum number of possible edges is now V*(V – 1)(with no multiple edges and self-loops).For directed graphs with no self-loops, we need to check if the two vertices chosen randomly, are equal. If they are not, then only create an edge between them.For directed graphs with no multiple edges, we need to check if there is already an edge between the randomly chosen vertices. If no such edge exists, then only create an edge between them.When creating an edge between two vertices, we only need to add w to the adjacency list of v and not v to the adjacency list of w as this is a directed graph. For a randomly chosen number of vertices V, the maximum number of possible edges is now V*(V – 1)(with no multiple edges and self-loops). For directed graphs with no self-loops, we need to check if the two vertices chosen randomly, are equal. If they are not, then only create an edge between them. For directed graphs with no multiple edges, we need to check if there is already an edge between the randomly chosen vertices. If no such edge exists, then only create an edge between them. When creating an edge between two vertices, we only need to add w to the adjacency list of v and not v to the adjacency list of w as this is a directed graph. Here is the code that creates random directed graphs with no multiple edges and self-loops — Java // Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the // number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // Randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // Check if there is already an edge between v // and w if ((v == w) || adjacencyList.get(v).contains(w)) { // Reduce the value of i // so that again v and w can be chosen // for the same edge count i = i - 1; continue; } // Add an edge between them if // not previously created addEdge(v, w); } } // Method to compute the maximum number of // possible edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is a directed graph // So, for a given number of vertices // there can be at-most v*(v-1) number of edges return numOfVertices * (numOfVertices - 1); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is a directed graph // Add w to v's adjacency list adjacencyList.get(v).add(w); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println("The generated random graph :"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + " -> { "); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(" No adjacent vertices "); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(" , "); } } System.out.println("}"); } }} The generated random graph : 0 -> { 4 , 3 , 5 , 15 , 13} 1 -> { 2 , 6 , 9 , 7 , 12 , 4} 2 -> { 4 , 7 , 13 , 12 , 11 , 9} 3 -> { 5 , 2 , 15 , 10} 4 -> { 2 , 16 , 8 , 7} 5 -> { 7 , 16 , 10 , 0 , 9} 6 -> { 12 , 11 , 14 , 2 , 5 , 16} 7 -> { 8 , 11 , 12 , 3 , 16 , 10 , 13} 8 -> { 6 , 7 , 15 , 12 , 0 , 5 , 9 , 16} 9 -> { 3 , 4 , 16} 10 -> { 9 , 12 , 16 , 6} 11 -> { 10 , 8 , 15 , 9 , 12 , 13} 12 -> { 5 , 7 , 10 , 1} 13 -> { 16 , 2 , 10 , 3 , 1} 14 -> { 3 , 15 , 8 , 12 , 7 , 1} 15 -> { 9 , 2 , 1 , 14 , 8 , 4} 16 -> { 1 , 2 , 9 , 3 , 10 , 7} The above output graph is a random directed graph with no self-loops and multiple edges. The algorithm 1 is based on randomly choosing a number of vertices v and edges e and creating a graph containing v vertices and e edges. The second algorithm we are going to discuss is based on Erdos-Renyi G(v,p) Random Graph model. Algorithm 2 (The Erdos-Renyi G(v,p) model) : The Erdos-Renyi G(v,p) model (named after Paul Erdos and Alfred Renyi) which is considered one of the first to attempt to describe the random networks, is one of the most popular models to generate random graphs. This model generates a random graph containing v vertices and edges between any two vertices with probability p. p is the probability that there is an edge between any two vertices. Randomly choose a number of vertices and the probability p. The value of p is between 0.0 to 1.0.Iterate over each pair of vertices and generate a random number between 0.0 and 1.0. If the randomly chosen number is less than the probability p, then add an edge between the two vertices of the pair. The number of edges in the graph totally depends on the probability p.Print the graph. Randomly choose a number of vertices and the probability p. The value of p is between 0.0 to 1.0. Iterate over each pair of vertices and generate a random number between 0.0 and 1.0. If the randomly chosen number is less than the probability p, then add an edge between the two vertices of the pair. The number of edges in the graph totally depends on the probability p. Print the graph. Below is the implementation of the above approach: Java // Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { // Number of vertices public int vertices; // p represents the probability public float p; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the // number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // p is the probability that there // is an edge between any two vertices // say, 0.4 is the probability that there // is an edge between any two vertices this.p = random.nextFloat(); // Print the probability p System.out.println( "The probability that there is an edge" + " between any two vertices is : " + p); // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < vertices; i++) { for (int j = 0; j < vertices; j++) { // edgeProbability is a random number // between 0.0 and 1.0 // If the randomly chosen number // edgeProbability is less than // the probability of an edge p, // say, edgeProbability = 0.2 which is less // than p = 0.4, then add an edge between the // vertex i and the vertex j float edgeProbability = random.nextFloat(); if (edgeProbability < p) addEdge(i, j); } } } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is a directed graph // Add w to v's adjacency list adjacencyList.get(v).add(w); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println("The generated random graph :"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + " -> { "); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(" No adjacent vertices "); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(" , "); } } System.out.println("}"); } }} The probability that there is an edge between any two vertices is : 0.8065328 The generated random graph : 0 -> { 0 , 1 , 2 , 3 , 5 , 6 , 7 , 8 , 11 , 13 , 14 , 15 , 16 , 17} 1 -> { 0 , 2 , 3 , 5 , 6 , 7 , 8 , 9 , 10 , 12 , 14 , 15 , 16 , 17} 2 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 8 , 9 , 10 , 11 , 13 , 15 , 16 , 17} 3 -> { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 4 -> { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 5 -> { 0 , 1 , 3 , 7 , 9 , 13 , 14 , 15 , 16 , 17} 6 -> { 1 , 2 , 3 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 7 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 8 , 9 , 10 , 12 , 13 , 15 , 16 , 17} 8 -> { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 9 -> { 0 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 10 -> { 0 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 17} 11 -> { 0 , 1 , 2 , 3 , 4 , 6 , 7 , 8 , 9 , 10 , 12 , 14 , 15 , 16 , 17} 12 -> { 0 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 11 , 12 , 13 , 14 , 15 , 16 , 17} 13 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 9 , 10 , 12 , 13 , 14 , 15 , 16 , 17} 14 -> { 1 , 2 , 3 , 4 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 17} 15 -> { 0 , 1 , 3 , 4 , 6 , 7 , 8 , 9 , 10 , 11 , 13 , 14 , 15 , 16} 16 -> { 0 , 1 , 2 , 3 , 5 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16} 17 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 9 , 10 , 13 , 14 , 15 , 16} The above program generates random directed graphs with self-loops. Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Multidimensional Arrays in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24259, "s": 24231, "text": "\n08 Dec, 2020" }, { "code": null, "e": 24808, "s": 24259, "text": "We know that Graph is a data structure that consists of a finite set of vertices and edges(that connect the vertices with each other). A graph can be directed(edges having a direction) or undirected(edges with no directions). However, a Random graph is a graph data structure that is generated randomly. Random Graph models are widely used in studying complex networks, social networks, communication engineering and even in biology(in studying intracellular regulatory networks, activating and inhibiting connections in biological networks etc.). " }, { "code": null, "e": 24909, "s": 24808, "text": "In this article, we are going to discuss some algorithms to generate various types of random graphs." }, { "code": null, "e": 24924, "s": 24909, "text": "Algorithm 1: " }, { "code": null, "e": 25072, "s": 24924, "text": "This algorithm is based on randomly choosing the number of vertices and edges and then randomly selecting two vertices to add an edge between them." }, { "code": null, "e": 25615, "s": 25072, "text": "Randomly choose the number of vertices and edges. Say, V be the number of vertices and E be the number of edgesCheck if the chosen number of edges E is compatible with the number of vertices. As for a chosen number of vertices V, there can be at-most (V*(V-1)/2) edges (Why V*(V – 1)/2 ? it is discussed later) in an undirected graph(if it does not contain self-loops).Run a for loop that runs for i = 0 to i < number of edges E, and during each iteration, randomly choose two vertices and create an edge between them.Print the created graph." }, { "code": null, "e": 25727, "s": 25615, "text": "Randomly choose the number of vertices and edges. Say, V be the number of vertices and E be the number of edges" }, { "code": null, "e": 25986, "s": 25727, "text": "Check if the chosen number of edges E is compatible with the number of vertices. As for a chosen number of vertices V, there can be at-most (V*(V-1)/2) edges (Why V*(V – 1)/2 ? it is discussed later) in an undirected graph(if it does not contain self-loops)." }, { "code": null, "e": 26136, "s": 25986, "text": "Run a for loop that runs for i = 0 to i < number of edges E, and during each iteration, randomly choose two vertices and create an edge between them." }, { "code": null, "e": 26161, "s": 26136, "text": "Print the created graph." }, { "code": null, "e": 26212, "s": 26161, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26217, "s": 26212, "text": "Java" }, { "code": "// Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for // the number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // add an edge between them addEdge(v, w); } } // Method to compute the maximum number of possible // edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is an undirected graph // So, for a given number of vertices // there can be at-most v*(v-1)/2 number of edges return numOfVertices * ((numOfVertices - 1) / 2); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is an Undirected graph // Add w to v's adjacency list adjacencyList.get(v).add(w); // Add v to w's adjacency list adjacencyList.get(w).add(v); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println(\"The generated random graph :\"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + \" -> { \"); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(\" No adjacent vertices \"); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(\" , \"); } } System.out.println(\"}\"); } }}", "e": 29160, "s": 26217, "text": null }, { "code": null, "e": 29773, "s": 29160, "text": "The generated random graph :\n0 -> { 7 , 10 , 7 , 2 , 8 , 7 , 1}\n1 -> { 5 , 8 , 8 , 3 , 4 , 12 , 8 , 7 , 9 , 0 , 7}\n2 -> { 2 , 2 , 7 , 0 , 2 , 2 , 11 , 12 , 3 , 9 , 4 , 2 , 2 , 12 , 5}\n3 -> { 6 , 10 , 1 , 12 , 11 , 2 , 10 , 10 , 3 , 3 , 5}\n4 -> { 1 , 8 , 6 , 8 , 8 , 2 , 5 , 11}\n5 -> { 1 , 5 , 5 , 8 , 4 , 2 , 11 , 3}\n6 -> { 3 , 9 , 12 , 4 , 10 , 8 , 9}\n7 -> { 0 , 2 , 0 , 12 , 1 , 7 , 7 , 12 , 0 , 8 , 1}\n8 -> { 5 , 1 , 1 , 0 , 1 , 4 , 4 , 4 , 6 , 11 , 7}\n9 -> { 6 , 12 , 1 , 2 , 9 , 9 , 6 , 9 , 9}\n10 -> { 3 , 0 , 3 , 3 , 10 , 10 , 6}\n11 -> { 3 , 2 , 12 , 8 , 4 , 5}\n12 -> { 7 , 3 , 9 , 1 , 6 , 11 , 2 , 7 , 2}\n" }, { "code": null, "e": 29853, "s": 29773, "text": "Each time you run the above program you will get a different undirected graph. " }, { "code": null, "e": 29892, "s": 29853, "text": "2. Remove the repetitions of the edges" }, { "code": null, "e": 30059, "s": 29892, "text": "Check if the edge already exists or not at run time. Using this approach complexity of the algorithm 1 will get increase but the optimization in the memory increases." }, { "code": null, "e": 30110, "s": 30059, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30115, "s": 30110, "text": "Java" }, { "code": "// Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the number // of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list representation // for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // Check if there is already // an edge between v and w if (adjacencyList.get(v).contains(w)) { // Reduce the value of i // so that again v and w can be chosen // for the same edge count i = i - 1; continue; } // Add an edge between them if // not previously created addEdge(v, w); } } // Method to compute the maximum number of possible // edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is an undirected graph // So, for a given number of vertices V // there can be at-most V*(V-1)/2 number of edges return numOfVertices * ((numOfVertices - 1) / 2); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is an Undirected graph // Add w to v's adjacency list adjacencyList.get(v).add(w); // Add v to w's adjacency list // if v is not equal to w if (v != w) adjacencyList.get(w).add(v); // The above condition is important // If you don't apply the condition then // two self-loops will be created if // v and w are equal } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println(\"The generated random graph :\"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + \" -> { \"); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(\" No adjacent vertices \"); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(\" , \"); } } System.out.println(\"}\"); } }}", "e": 33650, "s": 30115, "text": null }, { "code": null, "e": 34967, "s": 33650, "text": "The generated random graph :\n0 -> { 7 , 0 , 9 , 16 , 8 , 3 , 14 , 17 , 10 , 1 , 6 , 11 , 5 , 4 , 12}\n1 -> { 17 , 8 , 6 , 12 , 9 , 11 , 13 , 5 , 15 , 0 , 2 , 7 , 16 , 3}\n2 -> { 11 , 16 , 9 , 8 , 6 , 13 , 17 , 4 , 2 , 14 , 1 , 7 , 10}\n3 -> { 4 , 8 , 13 , 10 , 12 , 17 , 0 , 15 , 16 , 3 , 7 , 6 , 5 , 1}\n4 -> { 3 , 17 , 5 , 15 , 16 , 8 , 2 , 7 , 13 , 6 , 9 , 4 , 11 , 14 , 12 , 0}\n5 -> { 10 , 17 , 6 , 16 , 4 , 9 , 14 , 13 , 8 , 1 , 3 , 5 , 0 , 15 , 7}\n6 -> { 5 , 2 , 8 , 1 , 15 , 16 , 12 , 14 , 4 , 6 , 3 , 0 , 17 , 10 , 7}\n7 -> { 9 , 11 , 0 , 15 , 7 , 4 , 10 , 13 , 17 , 16 , 3 , 8 , 1 , 6 , 2 , 5 , 12}\n8 -> { 16 , 3 , 2 , 1 , 17 , 6 , 13 , 0 , 15 , 4 , 14 , 5 , 7 , 12 , 9 , 11}\n9 -> { 7 , 10 , 2 , 9 , 0 , 1 , 5 , 17 , 16 , 4 , 12 , 11 , 13 , 8}\n10 -> { 11 , 5 , 9 , 3 , 12 , 7 , 13 , 10 , 16 , 14 , 17 , 0 , 15 , 6 , 2}\n11 -> { 2 , 10 , 17 , 12 , 7 , 15 , 16 , 11 , 1 , 13 , 14 , 4 , 9 , 0 , 8}\n12 -> { 12 , 11 , 3 , 1 , 6 , 10 , 16 , 15 , 8 , 9 , 4 , 13 , 0 , 7}\n13 -> { 14 , 3 , 17 , 15 , 2 , 8 , 7 , 10 , 5 , 1 , 4 , 11 , 9 , 13 , 12}\n14 -> { 13 , 5 , 2 , 8 , 6 , 0 , 10 , 11 , 4 , 17 , 15}\n15 -> { 13 , 11 , 17 , 4 , 7 , 6 , 8 , 3 , 1 , 12 , 10 , 16 , 14 , 5}\n16 -> { 2 , 8 , 5 , 0 , 4 , 6 , 11 , 12 , 9 , 3 , 10 , 7 , 17 , 15 , 1}\n17 -> { 1 , 11 , 5 , 4 , 13 , 8 , 15 , 3 , 2 , 9 , 7 , 0 , 16 , 10 , 14 , 6}\n" }, { "code": null, "e": 35262, "s": 34967, "text": "Now the output undirected graph does not contain any multiple edges between the same vertices. Though the graph may contain self-loops(but now only one for each vertex). However, if you want to generate undirected graphs without self-loops, then you can add another condition to the above code " }, { "code": null, "e": 35532, "s": 35262, "text": "//Check if there is already an edge between v and w or v and w are equal\nif((v == w ) || adjacencyList.get(v).contains(w)) {\n //Reduce the value of i\n //so that again v and w can be chosen \n //for the same edge count\n i = i - 1;\n continue;\n}" }, { "code": null, "e": 35617, "s": 35532, "text": "Now, no self-loops and multiple edges are allowed in the generated undirected graph." }, { "code": null, "e": 35728, "s": 35617, "text": "Why for a given number of vertices V in an undirected graph, there can be at-most V*((V-1)/2) number of edges?" }, { "code": null, "e": 36257, "s": 35728, "text": "Suppose, there are V number of vertices in a directed graph. Now, if the graph doesn’t contain any self-loops and multiple edges, then each vertex can have (V-1) edges with other (V-1) vertices. So, V vertices can have at-most V*(V – 1) vertices. If the graph contains self-loops then the maximum possible number of edges is V2 (with no multiple edges). Because, each vertex can have an edge with itself also. So, for Undirected graphs, the maximum possible number of edges is V*(V – 1)/2 as the edges don’t have any directions." }, { "code": null, "e": 36430, "s": 36257, "text": "Till now, we have created random undirected graphs, however, if you want to create random directed graphs, then we have to make some changes to the above implemented code —" }, { "code": null, "e": 37075, "s": 36430, "text": "For a randomly chosen number of vertices V, the maximum number of possible edges is now V*(V – 1)(with no multiple edges and self-loops).For directed graphs with no self-loops, we need to check if the two vertices chosen randomly, are equal. If they are not, then only create an edge between them.For directed graphs with no multiple edges, we need to check if there is already an edge between the randomly chosen vertices. If no such edge exists, then only create an edge between them.When creating an edge between two vertices, we only need to add w to the adjacency list of v and not v to the adjacency list of w as this is a directed graph." }, { "code": null, "e": 37213, "s": 37075, "text": "For a randomly chosen number of vertices V, the maximum number of possible edges is now V*(V – 1)(with no multiple edges and self-loops)." }, { "code": null, "e": 37374, "s": 37213, "text": "For directed graphs with no self-loops, we need to check if the two vertices chosen randomly, are equal. If they are not, then only create an edge between them." }, { "code": null, "e": 37564, "s": 37374, "text": "For directed graphs with no multiple edges, we need to check if there is already an edge between the randomly chosen vertices. If no such edge exists, then only create an edge between them." }, { "code": null, "e": 37723, "s": 37564, "text": "When creating an edge between two vertices, we only need to add w to the adjacency list of v and not v to the adjacency list of w as this is a directed graph." }, { "code": null, "e": 37816, "s": 37723, "text": "Here is the code that creates random directed graphs with no multiple edges and self-loops —" }, { "code": null, "e": 37821, "s": 37816, "text": "Java" }, { "code": "// Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { public int vertices; public int edges; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the // number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // compute the maximum possible number of edges // and randomly choose the number of edges less than // or equal to the maximum number of possible edges this.edges = random.nextInt(computeMaxEdges(vertices)) + 1; // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < edges; i++) { // Randomly select two vertices to // create an edge between them int v = random.nextInt(vertices); int w = random.nextInt(vertices); // Check if there is already an edge between v // and w if ((v == w) || adjacencyList.get(v).contains(w)) { // Reduce the value of i // so that again v and w can be chosen // for the same edge count i = i - 1; continue; } // Add an edge between them if // not previously created addEdge(v, w); } } // Method to compute the maximum number of // possible edges for a given number of vertices int computeMaxEdges(int numOfVertices) { // As it is a directed graph // So, for a given number of vertices // there can be at-most v*(v-1) number of edges return numOfVertices * (numOfVertices - 1); } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is a directed graph // Add w to v's adjacency list adjacencyList.get(v).add(w); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println(\"The generated random graph :\"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + \" -> { \"); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(\" No adjacent vertices \"); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(\" , \"); } } System.out.println(\"}\"); } }}", "e": 41072, "s": 37821, "text": null }, { "code": null, "e": 41612, "s": 41072, "text": "The generated random graph :\n0 -> { 4 , 3 , 5 , 15 , 13}\n1 -> { 2 , 6 , 9 , 7 , 12 , 4}\n2 -> { 4 , 7 , 13 , 12 , 11 , 9}\n3 -> { 5 , 2 , 15 , 10}\n4 -> { 2 , 16 , 8 , 7}\n5 -> { 7 , 16 , 10 , 0 , 9}\n6 -> { 12 , 11 , 14 , 2 , 5 , 16}\n7 -> { 8 , 11 , 12 , 3 , 16 , 10 , 13}\n8 -> { 6 , 7 , 15 , 12 , 0 , 5 , 9 , 16}\n9 -> { 3 , 4 , 16}\n10 -> { 9 , 12 , 16 , 6}\n11 -> { 10 , 8 , 15 , 9 , 12 , 13}\n12 -> { 5 , 7 , 10 , 1}\n13 -> { 16 , 2 , 10 , 3 , 1}\n14 -> { 3 , 15 , 8 , 12 , 7 , 1}\n15 -> { 9 , 2 , 1 , 14 , 8 , 4}\n16 -> { 1 , 2 , 9 , 3 , 10 , 7}\n" }, { "code": null, "e": 41702, "s": 41612, "text": "The above output graph is a random directed graph with no self-loops and multiple edges. " }, { "code": null, "e": 41938, "s": 41704, "text": "The algorithm 1 is based on randomly choosing a number of vertices v and edges e and creating a graph containing v vertices and e edges. The second algorithm we are going to discuss is based on Erdos-Renyi G(v,p) Random Graph model. " }, { "code": null, "e": 41983, "s": 41938, "text": "Algorithm 2 (The Erdos-Renyi G(v,p) model) :" }, { "code": null, "e": 42378, "s": 41983, "text": "The Erdos-Renyi G(v,p) model (named after Paul Erdos and Alfred Renyi) which is considered one of the first to attempt to describe the random networks, is one of the most popular models to generate random graphs. This model generates a random graph containing v vertices and edges between any two vertices with probability p. p is the probability that there is an edge between any two vertices." }, { "code": null, "e": 42764, "s": 42378, "text": "Randomly choose a number of vertices and the probability p. The value of p is between 0.0 to 1.0.Iterate over each pair of vertices and generate a random number between 0.0 and 1.0. If the randomly chosen number is less than the probability p, then add an edge between the two vertices of the pair. The number of edges in the graph totally depends on the probability p.Print the graph." }, { "code": null, "e": 42862, "s": 42764, "text": "Randomly choose a number of vertices and the probability p. The value of p is between 0.0 to 1.0." }, { "code": null, "e": 43135, "s": 42862, "text": "Iterate over each pair of vertices and generate a random number between 0.0 and 1.0. If the randomly chosen number is less than the probability p, then add an edge between the two vertices of the pair. The number of edges in the graph totally depends on the probability p." }, { "code": null, "e": 43152, "s": 43135, "text": "Print the graph." }, { "code": null, "e": 43203, "s": 43152, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 43208, "s": 43203, "text": "Java" }, { "code": "// Create a Random Graph Using// Random Edge Generation in Javaimport java.util.*;import java.io.*; public class GFGRandomGraph { // Number of vertices public int vertices; // p represents the probability public float p; // Set a maximum limit to the vertices final int MAX_LIMIT = 20; // A Random instance to generate random values Random random = new Random(); // An adjacency list to represent a graph public List<List<Integer> > adjacencyList; // Creating the constructor public GFGRandomGraph() { // Set a maximum limit for the // number of vertices say 20 this.vertices = random.nextInt(MAX_LIMIT) + 1; // p is the probability that there // is an edge between any two vertices // say, 0.4 is the probability that there // is an edge between any two vertices this.p = random.nextFloat(); // Print the probability p System.out.println( \"The probability that there is an edge\" + \" between any two vertices is : \" + p); // Creating an adjacency list // representation for the random graph adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < vertices; i++) adjacencyList.add(new ArrayList<>()); // A for loop to randomly generate edges for (int i = 0; i < vertices; i++) { for (int j = 0; j < vertices; j++) { // edgeProbability is a random number // between 0.0 and 1.0 // If the randomly chosen number // edgeProbability is less than // the probability of an edge p, // say, edgeProbability = 0.2 which is less // than p = 0.4, then add an edge between the // vertex i and the vertex j float edgeProbability = random.nextFloat(); if (edgeProbability < p) addEdge(i, j); } } } // Method to add edges between given vertices void addEdge(int v, int w) { // Note: it is a directed graph // Add w to v's adjacency list adjacencyList.get(v).add(w); } public static void main(String[] args) { // Create a GFGRandomGraph object GFGRandomGraph randomGraph = new GFGRandomGraph(); // Print the graph System.out.println(\"The generated random graph :\"); for (int i = 0; i < randomGraph.adjacencyList.size(); i++) { System.out.print(i + \" -> { \"); List<Integer> list = randomGraph.adjacencyList.get(i); if (list.isEmpty()) System.out.print(\" No adjacent vertices \"); else { int size = list.size(); for (int j = 0; j < size; j++) { System.out.print(list.get(j)); if (j < size - 1) System.out.print(\" , \"); } } System.out.println(\"}\"); } }}", "e": 46262, "s": 43208, "text": null }, { "code": null, "e": 47679, "s": 46262, "text": "The probability that there is an edge between any two vertices is : 0.8065328\nThe generated random graph :\n0 -> { 0 , 1 , 2 , 3 , 5 , 6 , 7 , 8 , 11 , 13 , 14 , 15 , 16 , 17}\n1 -> { 0 , 2 , 3 , 5 , 6 , 7 , 8 , 9 , 10 , 12 , 14 , 15 , 16 , 17}\n2 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 8 , 9 , 10 , 11 , 13 , 15 , 16 , 17}\n3 -> { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n4 -> { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n5 -> { 0 , 1 , 3 , 7 , 9 , 13 , 14 , 15 , 16 , 17}\n6 -> { 1 , 2 , 3 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n7 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 8 , 9 , 10 , 12 , 13 , 15 , 16 , 17}\n8 -> { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n9 -> { 0 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n10 -> { 0 , 1 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 17}\n11 -> { 0 , 1 , 2 , 3 , 4 , 6 , 7 , 8 , 9 , 10 , 12 , 14 , 15 , 16 , 17}\n12 -> { 0 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 11 , 12 , 13 , 14 , 15 , 16 , 17}\n13 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 9 , 10 , 12 , 13 , 14 , 15 , 16 , 17}\n14 -> { 1 , 2 , 3 , 4 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 17}\n15 -> { 0 , 1 , 3 , 4 , 6 , 7 , 8 , 9 , 10 , 11 , 13 , 14 , 15 , 16}\n16 -> { 0 , 1 , 2 , 3 , 5 , 6 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16}\n17 -> { 0 , 1 , 2 , 3 , 4 , 5 , 7 , 9 , 10 , 13 , 14 , 15 , 16}\n" }, { "code": null, "e": 47747, "s": 47679, "text": "The above program generates random directed graphs with self-loops." }, { "code": null, "e": 47754, "s": 47747, "text": "Picked" }, { "code": null, "e": 47759, "s": 47754, "text": "Java" }, { "code": null, "e": 47773, "s": 47759, "text": "Java Programs" }, { "code": null, "e": 47778, "s": 47773, "text": "Java" }, { "code": null, "e": 47876, "s": 47778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47885, "s": 47876, "text": "Comments" }, { "code": null, "e": 47898, "s": 47885, "text": "Old Comments" }, { "code": null, "e": 47928, "s": 47898, "text": "HashMap in Java with Examples" }, { "code": null, "e": 47947, "s": 47928, "text": "Interfaces in Java" }, { "code": null, "e": 47979, "s": 47947, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 47997, "s": 47979, "text": "ArrayList in Java" }, { "code": null, "e": 48029, "s": 47997, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 48073, "s": 48029, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 48101, "s": 48073, "text": "Initializing a List in Java" }, { "code": null, "e": 48127, "s": 48101, "text": "Java Programming Examples" }, { "code": null, "e": 48161, "s": 48127, "text": "Convert Double to Integer in Java" } ]
Basic Calculator in C++
Suppose we want to create one basic calculator that will find the basic expression result. The expression can hold opening and closing parentheses, plus or minus symbol and empty spaces. So if the string is like “5 + 2 - 3”, then the result will be 7 To solve this, we will follow these steps − ret := 0, sign := 1, num := 0, n := size of s ret := 0, sign := 1, num := 0, n := size of s Define one stack st Define one stack st for initializing i := 0, when i < n, increase i by 1 do −Define an array x = s of size iif x >= '0' and x <= '9', then,num = num * 10num = num + (x - '0')Otherwise when x is same as '(', then −ret = ret + (sign * num)insert ret into stinsert sign into stret := 0, sign := 1, num := 0Otherwise when x is same as ')', then −ret = ret + (sign * num), sign := 1, num := 0ret = ret * top element of stdelete item from stret = ret + top element of stdelete item from stOtherwise when x is same as '+', then −ret = ret + (sign * num), sign := 1, num := 0Otherwise when x is same as '-', then −ret = ret + (sign * num), sign := - 1, num := 0 for initializing i := 0, when i < n, increase i by 1 do − Define an array x = s of size i Define an array x = s of size i if x >= '0' and x <= '9', then,num = num * 10num = num + (x - '0') if x >= '0' and x <= '9', then, num = num * 10 num = num * 10 num = num + (x - '0') num = num + (x - '0') Otherwise when x is same as '(', then −ret = ret + (sign * num)insert ret into stinsert sign into stret := 0, sign := 1, num := 0 Otherwise when x is same as '(', then − ret = ret + (sign * num) ret = ret + (sign * num) insert ret into st insert ret into st insert sign into st insert sign into st ret := 0, sign := 1, num := 0 ret := 0, sign := 1, num := 0 Otherwise when x is same as ')', then −ret = ret + (sign * num), sign := 1, num := 0ret = ret * top element of stdelete item from stret = ret + top element of stdelete item from st Otherwise when x is same as ')', then − ret = ret + (sign * num), sign := 1, num := 0 ret = ret + (sign * num), sign := 1, num := 0 ret = ret * top element of st ret = ret * top element of st delete item from st delete item from st ret = ret + top element of st ret = ret + top element of st delete item from st delete item from st Otherwise when x is same as '+', then −ret = ret + (sign * num), sign := 1, num := 0 Otherwise when x is same as '+', then − ret = ret + (sign * num), sign := 1, num := 0 ret = ret + (sign * num), sign := 1, num := 0 Otherwise when x is same as '-', then −ret = ret + (sign * num), sign := - 1, num := 0 Otherwise when x is same as '-', then − ret = ret + (sign * num), sign := - 1, num := 0 ret = ret + (sign * num), sign := - 1, num := 0 if num is non-zero, then,ret = ret + sign * num if num is non-zero, then, ret = ret + sign * num ret = ret + sign * num return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int calculate(string s) { int ret = 0; int sign = 1; int num = 0; int n = s.size(); stack <int> st; for(int i = 0; i < n; ++i){ char x = s[i]; if(x >= '0' && x <= '9'){ num *= 10; num += (x - '0'); } else if(x == '('){ ret += (sign * num); st.push(ret); st.push(sign); ret = 0; sign = 1; num = 0; } else if(x == ')'){ ret += (sign * num); sign = 1; num = 0; ret *= st.top(); st.pop(); ret += st.top(); st.pop(); } else if(x == '+'){ ret += (sign * num); sign = 1; num = 0; } else if(x == '-'){ ret += (sign * num); sign = -1; num = 0; } } if(num){ ret += sign * num; } return ret; } }; main(){ Solution ob; cout << (ob.calculate("5 + 2 - 3")); } "5 + 2 - 3" 4
[ { "code": null, "e": 1249, "s": 1062, "text": "Suppose we want to create one basic calculator that will find the basic expression result. The expression can hold opening and closing parentheses, plus or minus symbol and empty spaces." }, { "code": null, "e": 1313, "s": 1249, "text": "So if the string is like “5 + 2 - 3”, then the result will be 7" }, { "code": null, "e": 1357, "s": 1313, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1403, "s": 1357, "text": "ret := 0, sign := 1, num := 0, n := size of s" }, { "code": null, "e": 1449, "s": 1403, "text": "ret := 0, sign := 1, num := 0, n := size of s" }, { "code": null, "e": 1469, "s": 1449, "text": "Define one stack st" }, { "code": null, "e": 1489, "s": 1469, "text": "Define one stack st" }, { "code": null, "e": 2123, "s": 1489, "text": "for initializing i := 0, when i < n, increase i by 1 do −Define an array x = s of size iif x >= '0' and x <= '9', then,num = num * 10num = num + (x - '0')Otherwise when x is same as '(', then −ret = ret + (sign * num)insert ret into stinsert sign into stret := 0, sign := 1, num := 0Otherwise when x is same as ')', then −ret = ret + (sign * num), sign := 1, num := 0ret = ret * top element of stdelete item from stret = ret + top element of stdelete item from stOtherwise when x is same as '+', then −ret = ret + (sign * num), sign := 1, num := 0Otherwise when x is same as '-', then −ret = ret + (sign * num), sign := - 1, num := 0" }, { "code": null, "e": 2181, "s": 2123, "text": "for initializing i := 0, when i < n, increase i by 1 do −" }, { "code": null, "e": 2213, "s": 2181, "text": "Define an array x = s of size i" }, { "code": null, "e": 2245, "s": 2213, "text": "Define an array x = s of size i" }, { "code": null, "e": 2312, "s": 2245, "text": "if x >= '0' and x <= '9', then,num = num * 10num = num + (x - '0')" }, { "code": null, "e": 2344, "s": 2312, "text": "if x >= '0' and x <= '9', then," }, { "code": null, "e": 2359, "s": 2344, "text": "num = num * 10" }, { "code": null, "e": 2374, "s": 2359, "text": "num = num * 10" }, { "code": null, "e": 2396, "s": 2374, "text": "num = num + (x - '0')" }, { "code": null, "e": 2418, "s": 2396, "text": "num = num + (x - '0')" }, { "code": null, "e": 2548, "s": 2418, "text": "Otherwise when x is same as '(', then −ret = ret + (sign * num)insert ret into stinsert sign into stret := 0, sign := 1, num := 0" }, { "code": null, "e": 2588, "s": 2548, "text": "Otherwise when x is same as '(', then −" }, { "code": null, "e": 2613, "s": 2588, "text": "ret = ret + (sign * num)" }, { "code": null, "e": 2638, "s": 2613, "text": "ret = ret + (sign * num)" }, { "code": null, "e": 2657, "s": 2638, "text": "insert ret into st" }, { "code": null, "e": 2676, "s": 2657, "text": "insert ret into st" }, { "code": null, "e": 2696, "s": 2676, "text": "insert sign into st" }, { "code": null, "e": 2716, "s": 2696, "text": "insert sign into st" }, { "code": null, "e": 2746, "s": 2716, "text": "ret := 0, sign := 1, num := 0" }, { "code": null, "e": 2776, "s": 2746, "text": "ret := 0, sign := 1, num := 0" }, { "code": null, "e": 2957, "s": 2776, "text": "Otherwise when x is same as ')', then −ret = ret + (sign * num), sign := 1, num := 0ret = ret * top element of stdelete item from stret = ret + top element of stdelete item from st" }, { "code": null, "e": 2997, "s": 2957, "text": "Otherwise when x is same as ')', then −" }, { "code": null, "e": 3043, "s": 2997, "text": "ret = ret + (sign * num), sign := 1, num := 0" }, { "code": null, "e": 3089, "s": 3043, "text": "ret = ret + (sign * num), sign := 1, num := 0" }, { "code": null, "e": 3119, "s": 3089, "text": "ret = ret * top element of st" }, { "code": null, "e": 3149, "s": 3119, "text": "ret = ret * top element of st" }, { "code": null, "e": 3169, "s": 3149, "text": "delete item from st" }, { "code": null, "e": 3189, "s": 3169, "text": "delete item from st" }, { "code": null, "e": 3219, "s": 3189, "text": "ret = ret + top element of st" }, { "code": null, "e": 3249, "s": 3219, "text": "ret = ret + top element of st" }, { "code": null, "e": 3269, "s": 3249, "text": "delete item from st" }, { "code": null, "e": 3289, "s": 3269, "text": "delete item from st" }, { "code": null, "e": 3374, "s": 3289, "text": "Otherwise when x is same as '+', then −ret = ret + (sign * num), sign := 1, num := 0" }, { "code": null, "e": 3414, "s": 3374, "text": "Otherwise when x is same as '+', then −" }, { "code": null, "e": 3460, "s": 3414, "text": "ret = ret + (sign * num), sign := 1, num := 0" }, { "code": null, "e": 3506, "s": 3460, "text": "ret = ret + (sign * num), sign := 1, num := 0" }, { "code": null, "e": 3593, "s": 3506, "text": "Otherwise when x is same as '-', then −ret = ret + (sign * num), sign := - 1, num := 0" }, { "code": null, "e": 3633, "s": 3593, "text": "Otherwise when x is same as '-', then −" }, { "code": null, "e": 3681, "s": 3633, "text": "ret = ret + (sign * num), sign := - 1, num := 0" }, { "code": null, "e": 3729, "s": 3681, "text": "ret = ret + (sign * num), sign := - 1, num := 0" }, { "code": null, "e": 3777, "s": 3729, "text": "if num is non-zero, then,ret = ret + sign * num" }, { "code": null, "e": 3803, "s": 3777, "text": "if num is non-zero, then," }, { "code": null, "e": 3826, "s": 3803, "text": "ret = ret + sign * num" }, { "code": null, "e": 3849, "s": 3826, "text": "ret = ret + sign * num" }, { "code": null, "e": 3860, "s": 3849, "text": "return ret" }, { "code": null, "e": 3871, "s": 3860, "text": "return ret" }, { "code": null, "e": 3941, "s": 3871, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3952, "s": 3941, "text": " Live Demo" }, { "code": null, "e": 5104, "s": 3952, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int calculate(string s) {\n int ret = 0;\n int sign = 1;\n int num = 0;\n int n = s.size();\n stack <int> st;\n for(int i = 0; i < n; ++i){\n char x = s[i];\n if(x >= '0' && x <= '9'){\n num *= 10;\n num += (x - '0');\n }\n else if(x == '('){\n ret += (sign * num);\n st.push(ret);\n st.push(sign);\n ret = 0;\n sign = 1;\n num = 0;\n }\n else if(x == ')'){\n ret += (sign * num);\n sign = 1;\n num = 0;\n ret *= st.top();\n st.pop();\n ret += st.top();\n st.pop();\n }\n else if(x == '+'){\n ret += (sign * num);\n sign = 1;\n num = 0;\n }\n else if(x == '-'){\n ret += (sign * num);\n sign = -1;\n num = 0;\n }\n }\n if(num){\n ret += sign * num;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.calculate(\"5 + 2 - 3\"));\n}" }, { "code": null, "e": 5116, "s": 5104, "text": "\"5 + 2 - 3\"" }, { "code": null, "e": 5118, "s": 5116, "text": "4" } ]
How to create an array for JSON using PHP? - GeeksforGeeks
03 Dec, 2021 In this article, we will see how to create an array for the JSON in PHP, & will see its implementation through examples. Array: Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. An array is created using an array() function in PHP. There are 3 types of array in PHP that are listed below: Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value. Associative Array: It is used to store key-value pairs. Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays. For this purpose, we will use an associative array that uses a key-value type structure for storing data. These keys will be a string or an integer which will be used as an index to search the corresponding value in the array. The json_encode() function is used to convert the value of the array into JSON. This function is added in from PHP5. Also, you can make more nesting of arrays as per your requirement. You can also create an array of array of objects with this function. As in JSON, everything is stored as a key-value pair we will convert these key-value pairs of PHP arrays to JSON which can be used to send the response from the REST API server. Example 1: The below example is to convert an array into JSON. PHP <?php // Create an array that contains another // array with key value pair $arr = array ( // Every array will be converted // to an object array( "name" => "Pankaj Singh", "age" => "20" ), array( "name" => "Arun Yadav", "age" => "21" ), array( "name" => "Apeksha Jaiswal", "age" => "20" ) ); // Function to convert array into JSON echo json_encode($arr);?> [{"name":"Pankaj Singh","age":"20"}, {"name":"Arun Yadav","age":"21"}, {"name":"Apeksha Jaiswal","age":"20"}] Example 2: This example illustrates the conversion of the 2D associative array into JSON. PHP <?php // Declare two dimensional associative // array and initialize it $arr = array ( "first"=>array( "id"=>1, "product_name"=>"Doorbell", "cost"=>199 ), "second"=>array( "id"=>2, "product_name"=>"Bottle", "cost"=>99 ), "third"=>array( "id"=>3, "product_name"=>"Washing Machine", "cost"=>7999 ) ); // Function to convert array into JSON echo json_encode($arr);?> {"first":{"id":1,"product_name":"Doorbell","cost":199}, "second":{"id":2,"product_name":"Bottle","cost":99}, "third":{"id":3,"product_name":"Washing Machine","cost":7999}} sweetyty bhaskargeeksforgeeks JSON PHP-Questions Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? How to create admin login page using PHP? How to Install php-curl in Ubuntu ?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24702, "s": 24581, "text": "In this article, we will see how to create an array for the JSON in PHP, & will see its implementation through examples." }, { "code": null, "e": 25145, "s": 24702, "text": "Array: Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. An array is created using an array() function in PHP. There are 3 types of array in PHP that are listed below:" }, { "code": null, "e": 25288, "s": 25145, "text": "Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value." }, { "code": null, "e": 25344, "s": 25288, "text": "Associative Array: It is used to store key-value pairs." }, { "code": null, "e": 25529, "s": 25344, "text": "Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays. " }, { "code": null, "e": 26187, "s": 25529, "text": "For this purpose, we will use an associative array that uses a key-value type structure for storing data. These keys will be a string or an integer which will be used as an index to search the corresponding value in the array. The json_encode() function is used to convert the value of the array into JSON. This function is added in from PHP5. Also, you can make more nesting of arrays as per your requirement. You can also create an array of array of objects with this function. As in JSON, everything is stored as a key-value pair we will convert these key-value pairs of PHP arrays to JSON which can be used to send the response from the REST API server." }, { "code": null, "e": 26251, "s": 26187, "text": "Example 1: The below example is to convert an array into JSON. " }, { "code": null, "e": 26255, "s": 26251, "text": "PHP" }, { "code": "<?php // Create an array that contains another // array with key value pair $arr = array ( // Every array will be converted // to an object array( \"name\" => \"Pankaj Singh\", \"age\" => \"20\" ), array( \"name\" => \"Arun Yadav\", \"age\" => \"21\" ), array( \"name\" => \"Apeksha Jaiswal\", \"age\" => \"20\" ) ); // Function to convert array into JSON echo json_encode($arr);?>", "e": 26719, "s": 26255, "text": null }, { "code": null, "e": 26829, "s": 26719, "text": "[{\"name\":\"Pankaj Singh\",\"age\":\"20\"},\n{\"name\":\"Arun Yadav\",\"age\":\"21\"},\n{\"name\":\"Apeksha Jaiswal\",\"age\":\"20\"}]" }, { "code": null, "e": 26921, "s": 26831, "text": "Example 2: This example illustrates the conversion of the 2D associative array into JSON." }, { "code": null, "e": 26925, "s": 26921, "text": "PHP" }, { "code": "<?php // Declare two dimensional associative // array and initialize it $arr = array ( \"first\"=>array( \"id\"=>1, \"product_name\"=>\"Doorbell\", \"cost\"=>199 ), \"second\"=>array( \"id\"=>2, \"product_name\"=>\"Bottle\", \"cost\"=>99 ), \"third\"=>array( \"id\"=>3, \"product_name\"=>\"Washing Machine\", \"cost\"=>7999 ) ); // Function to convert array into JSON echo json_encode($arr);?>", "e": 27410, "s": 26925, "text": null }, { "code": null, "e": 27582, "s": 27410, "text": "{\"first\":{\"id\":1,\"product_name\":\"Doorbell\",\"cost\":199},\n\"second\":{\"id\":2,\"product_name\":\"Bottle\",\"cost\":99},\n\"third\":{\"id\":3,\"product_name\":\"Washing Machine\",\"cost\":7999}}" }, { "code": null, "e": 27593, "s": 27584, "text": "sweetyty" }, { "code": null, "e": 27614, "s": 27593, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27619, "s": 27614, "text": "JSON" }, { "code": null, "e": 27633, "s": 27619, "text": "PHP-Questions" }, { "code": null, "e": 27640, "s": 27633, "text": "Picked" }, { "code": null, "e": 27644, "s": 27640, "text": "PHP" }, { "code": null, "e": 27657, "s": 27644, "text": "PHP Programs" }, { "code": null, "e": 27674, "s": 27657, "text": "Web Technologies" }, { "code": null, "e": 27678, "s": 27674, "text": "PHP" }, { "code": null, "e": 27776, "s": 27678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27785, "s": 27776, "text": "Comments" }, { "code": null, "e": 27798, "s": 27785, "text": "Old Comments" }, { "code": null, "e": 27880, "s": 27798, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27944, "s": 27880, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 28018, "s": 27944, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 28060, "s": 28018, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 28111, "s": 28060, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 28163, "s": 28111, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28245, "s": 28163, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28309, "s": 28245, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 28351, "s": 28309, "text": "How to create admin login page using PHP?" } ]
How to detect page zoom level in all modern browsers using JavaScript ? - GeeksforGeeks
15 Jul, 2020 In this article, we will discuss how the current amount of zoom can be found on a webpage. Method 1: Using outerWidth and innerWidth Property: It is easier to detect the zoom level in webkit browsers like Chrome and Microsoft Edge. This method uses the outerWidth and innerWidthproperties, which are the inbuilt function of JavaScript. The outerWidth is first subtracted by 10, to account for the scrollbar and then divided with the innerWidth to get the zoom level. Note: The amount of zoom may not be exactly the amount of zoom shown by the browser. This can be solved by rounding off the value. Syntax: let zoom = (( window.outerWidth - 10 ) / window.innerWidth) * 100; Example: HTML <!DOCTYPE html><html lang="en"> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Zoom in or out of the page to get the current zoom value </b> <p>Current Zoom Level: <span class="output"> </span> </p> <script> window.addEventListener( "resize", getSizes, false); let out = document.querySelector(".output"); function getSizes() { let zoom = ((window.outerWidth - 10) / window.innerWidth) * 100; out.textContent = zoom; } </script></body> </html> Output: Method 2: Using clientWidth and clientHeight Property: As finding the amount of zoom is not possible in several browsers, the dimensions of the website can be found out and the operation can be done using these dimensions of the page. This method uses the clientWidth and clientHeigh properties, which are the inbuilt function of JavaScript. Syntax: let zoom = body.clientWidth + "px x " + body.clientHeight + "px"; Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> /* Set the body to occupy the whole browser window when there is less content */ body { height: 100vh; margin: 0; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Zoom in or out of the page to get the current zoom value </b> <p> Current Zoom Level in pixels: <span class="output"> </span> </p> <script> window.addEventListener( "resize", getSizes, false); let out = document.querySelector(".output"); function getSizes() { let body = document.body; let zoom = body.clientWidth + "px x " + body.clientHeight + "px"; out.textContent = zoom; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked 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 set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 26731, "s": 26703, "text": "\n15 Jul, 2020" }, { "code": null, "e": 26822, "s": 26731, "text": "In this article, we will discuss how the current amount of zoom can be found on a webpage." }, { "code": null, "e": 27198, "s": 26822, "text": "Method 1: Using outerWidth and innerWidth Property: It is easier to detect the zoom level in webkit browsers like Chrome and Microsoft Edge. This method uses the outerWidth and innerWidthproperties, which are the inbuilt function of JavaScript. The outerWidth is first subtracted by 10, to account for the scrollbar and then divided with the innerWidth to get the zoom level." }, { "code": null, "e": 27329, "s": 27198, "text": "Note: The amount of zoom may not be exactly the amount of zoom shown by the browser. This can be solved by rounding off the value." }, { "code": null, "e": 27337, "s": 27329, "text": "Syntax:" }, { "code": null, "e": 27404, "s": 27337, "text": "let zoom = (( window.outerWidth - 10 ) / window.innerWidth) * 100;" }, { "code": null, "e": 27413, "s": 27404, "text": "Example:" }, { "code": null, "e": 27418, "s": 27413, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Zoom in or out of the page to get the current zoom value </b> <p>Current Zoom Level: <span class=\"output\"> </span> </p> <script> window.addEventListener( \"resize\", getSizes, false); let out = document.querySelector(\".output\"); function getSizes() { let zoom = ((window.outerWidth - 10) / window.innerWidth) * 100; out.textContent = zoom; } </script></body> </html>", "e": 28037, "s": 27418, "text": null }, { "code": null, "e": 28045, "s": 28037, "text": "Output:" }, { "code": null, "e": 28387, "s": 28045, "text": "Method 2: Using clientWidth and clientHeight Property: As finding the amount of zoom is not possible in several browsers, the dimensions of the website can be found out and the operation can be done using these dimensions of the page. This method uses the clientWidth and clientHeigh properties, which are the inbuilt function of JavaScript." }, { "code": null, "e": 28395, "s": 28387, "text": "Syntax:" }, { "code": null, "e": 28461, "s": 28395, "text": "let zoom = body.clientWidth + \"px x \" + body.clientHeight + \"px\";" }, { "code": null, "e": 28470, "s": 28461, "text": "Example:" }, { "code": null, "e": 28475, "s": 28470, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Set the body to occupy the whole browser window when there is less content */ body { height: 100vh; margin: 0; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Zoom in or out of the page to get the current zoom value </b> <p> Current Zoom Level in pixels: <span class=\"output\"> </span> </p> <script> window.addEventListener( \"resize\", getSizes, false); let out = document.querySelector(\".output\"); function getSizes() { let body = document.body; let zoom = body.clientWidth + \"px x \" + body.clientHeight + \"px\"; out.textContent = zoom; } </script></body> </html>", "e": 29369, "s": 28475, "text": null }, { "code": null, "e": 29377, "s": 29369, "text": "Output:" }, { "code": null, "e": 29386, "s": 29377, "text": "CSS-Misc" }, { "code": null, "e": 29396, "s": 29386, "text": "HTML-Misc" }, { "code": null, "e": 29412, "s": 29396, "text": "JavaScript-Misc" }, { "code": null, "e": 29419, "s": 29412, "text": "Picked" }, { "code": null, "e": 29423, "s": 29419, "text": "CSS" }, { "code": null, "e": 29428, "s": 29423, "text": "HTML" }, { "code": null, "e": 29439, "s": 29428, "text": "JavaScript" }, { "code": null, "e": 29456, "s": 29439, "text": "Web Technologies" }, { "code": null, "e": 29483, "s": 29456, "text": "Web technologies Questions" }, { "code": null, "e": 29488, "s": 29483, "text": "HTML" }, { "code": null, "e": 29586, "s": 29488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29625, "s": 29586, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29662, "s": 29625, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29691, "s": 29662, "text": "Form validation using jQuery" }, { "code": null, "e": 29726, "s": 29691, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29768, "s": 29726, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29828, "s": 29768, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29881, "s": 29828, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29942, "s": 29881, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29966, "s": 29942, "text": "REST API (Introduction)" } ]
ReactJS Reactstrap Progress Component - GeeksforGeeks
22 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Progress component allows the user to display the current progress of an operation flow. We can use the following approach in ReactJS to use the ReactJS Reactstrap Progress Component. Progress Props: multi: It is used to indicate whether to show multiple progress or not. bar: It is used in combination with multi prop. tag: It is used to denote the tag for this component. value: It is used to denote the value of the progress. max: It is the maximum value that progress can reach. min: It is the minimum value that progress can begin from. animated: It is used to indicate whether to show animation or not. striped: It is used to indicate whether to show striped style or not. color: It is used to denote the color of the progress component. className: It is used to denote the class name for styling. barStyle: used to add style to the inner progress-bar element barClassName: used to add class to the inner progress-bar element barAriaValueText: It is used to denote the text value of bar aria value. barAriaLabelledBy: It is used to denote the bar aria labelled value Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here we have shown Progress with the multi prop. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Progress } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Progress Component</h4> <Progress multi> <Progress bar color="success" value="30" /> <Progress bar color="danger" value="40" /> <Progress bar color="warning" value="30" /> </Progress> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here we have shown Progress without the multi prop. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Progress } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Progress Component</h4> <Progress value={50} /> <br></br> <Progress value={70} /> <br></br> <Progress value={100} /> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/progress/ Reactstrap JavaScript ReactJS 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? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26557, "s": 26529, "text": "\n22 Jul, 2021" }, { "code": null, "e": 26907, "s": 26557, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Progress component allows the user to display the current progress of an operation flow. We can use the following approach in ReactJS to use the ReactJS Reactstrap Progress Component." }, { "code": null, "e": 26923, "s": 26907, "text": "Progress Props:" }, { "code": null, "e": 26995, "s": 26923, "text": "multi: It is used to indicate whether to show multiple progress or not." }, { "code": null, "e": 27043, "s": 26995, "text": "bar: It is used in combination with multi prop." }, { "code": null, "e": 27098, "s": 27043, "text": "tag: It is used to denote the tag for this component. " }, { "code": null, "e": 27153, "s": 27098, "text": "value: It is used to denote the value of the progress." }, { "code": null, "e": 27207, "s": 27153, "text": "max: It is the maximum value that progress can reach." }, { "code": null, "e": 27266, "s": 27207, "text": "min: It is the minimum value that progress can begin from." }, { "code": null, "e": 27333, "s": 27266, "text": "animated: It is used to indicate whether to show animation or not." }, { "code": null, "e": 27403, "s": 27333, "text": "striped: It is used to indicate whether to show striped style or not." }, { "code": null, "e": 27468, "s": 27403, "text": "color: It is used to denote the color of the progress component." }, { "code": null, "e": 27528, "s": 27468, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 27590, "s": 27528, "text": "barStyle: used to add style to the inner progress-bar element" }, { "code": null, "e": 27656, "s": 27590, "text": "barClassName: used to add class to the inner progress-bar element" }, { "code": null, "e": 27729, "s": 27656, "text": "barAriaValueText: It is used to denote the text value of bar aria value." }, { "code": null, "e": 27797, "s": 27729, "text": "barAriaLabelledBy: It is used to denote the bar aria labelled value" }, { "code": null, "e": 27847, "s": 27797, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 27943, "s": 27847, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername " }, { "code": null, "e": 28007, "s": 27943, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 28039, "s": 28007, "text": "npx create-react-app foldername" }, { "code": null, "e": 28154, "s": 28041, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 28254, "s": 28154, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 28268, "s": 28254, "text": "cd foldername" }, { "code": null, "e": 28405, "s": 28268, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap" }, { "code": null, "e": 28510, "s": 28405, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 28543, "s": 28510, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 28595, "s": 28543, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28613, "s": 28595, "text": "Project Structure" }, { "code": null, "e": 28727, "s": 28613, "text": "Example 1: Now write down the following code in the App.js file. Here we have shown Progress with the multi prop." }, { "code": null, "e": 28734, "s": 28727, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Progress } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Progress Component</h4> <Progress multi> <Progress bar color=\"success\" value=\"30\" /> <Progress bar color=\"danger\" value=\"40\" /> <Progress bar color=\"warning\" value=\"30\" /> </Progress> </div> );} export default App;", "e": 29285, "s": 28734, "text": null }, { "code": null, "e": 29398, "s": 29285, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29408, "s": 29398, "text": "npm start" }, { "code": null, "e": 29507, "s": 29408, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29624, "s": 29507, "text": "Example 2: Now write down the following code in the App.js file. Here we have shown Progress without the multi prop." }, { "code": null, "e": 29631, "s": 29624, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Progress } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Progress Component</h4> <Progress value={50} /> <br></br> <Progress value={70} /> <br></br> <Progress value={100} /> </div> );} export default App;", "e": 30081, "s": 29631, "text": null }, { "code": null, "e": 30194, "s": 30081, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30204, "s": 30194, "text": "npm start" }, { "code": null, "e": 30303, "s": 30204, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30364, "s": 30303, "text": "Reference: https://reactstrap.github.io/components/progress/" }, { "code": null, "e": 30375, "s": 30364, "text": "Reactstrap" }, { "code": null, "e": 30386, "s": 30375, "text": "JavaScript" }, { "code": null, "e": 30394, "s": 30386, "text": "ReactJS" }, { "code": null, "e": 30411, "s": 30394, "text": "Web Technologies" }, { "code": null, "e": 30509, "s": 30411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30549, "s": 30509, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30610, "s": 30549, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30651, "s": 30610, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30673, "s": 30651, "text": "JavaScript | Promises" }, { "code": null, "e": 30727, "s": 30673, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30770, "s": 30727, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30815, "s": 30770, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 30880, "s": 30815, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 30948, "s": 30880, "text": "How to pass data from one component to other component in ReactJS ?" } ]
BufferedWriter close() method in Java with Examples - GeeksforGeeks
28 May, 2020 The close() method of BufferedWriter class in Java is used to flush the characters from the buffer stream and then close it. Once the stream is closed further calling the methods like write() and append() will throw the exception. Syntax: public void close() Parameters: This method does not accept any parameter. Return value: This method does not return any value. Exceptions: This method throws IOException if an I/O error occurs. Below programs illustrate close() method in BufferedWriter class in IO package: Program 1: // Java program to illustrate// BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); } catch (Exception e) { System.out.println( "BufferedWriter is closed"); } }} GEEKS Program 2: // Java program to illustrate// BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); // It will throw exception buffWriter.write( "GEEKSFORGEEKS", 5, 8); } catch (Exception e) { System.out.println( "BufferedWriter is closed"); } }} GEEKS BufferedWriter is closed Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close() Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n28 May, 2020" }, { "code": null, "e": 25578, "s": 25347, "text": "The close() method of BufferedWriter class in Java is used to flush the characters from the buffer stream and then close it. Once the stream is closed further calling the methods like write() and append() will throw the exception." }, { "code": null, "e": 25586, "s": 25578, "text": "Syntax:" }, { "code": null, "e": 25607, "s": 25586, "text": "public void close()\n" }, { "code": null, "e": 25662, "s": 25607, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 25715, "s": 25662, "text": "Return value: This method does not return any value." }, { "code": null, "e": 25782, "s": 25715, "text": "Exceptions: This method throws IOException if an I/O error occurs." }, { "code": null, "e": 25862, "s": 25782, "text": "Below programs illustrate close() method in BufferedWriter class in IO package:" }, { "code": null, "e": 25873, "s": 25862, "text": "Program 1:" }, { "code": "// Java program to illustrate// BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); } catch (Exception e) { System.out.println( \"BufferedWriter is closed\"); } }}", "e": 26719, "s": 25873, "text": null }, { "code": null, "e": 26726, "s": 26719, "text": "GEEKS\n" }, { "code": null, "e": 26737, "s": 26726, "text": "Program 2:" }, { "code": "// Java program to illustrate// BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffered writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); // It will throw exception buffWriter.write( \"GEEKSFORGEEKS\", 5, 8); } catch (Exception e) { System.out.println( \"BufferedWriter is closed\"); } }}", "e": 27691, "s": 26737, "text": null }, { "code": null, "e": 27723, "s": 27691, "text": "GEEKS\nBufferedWriter is closed\n" }, { "code": null, "e": 27812, "s": 27723, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close()" }, { "code": null, "e": 27828, "s": 27812, "text": "Java-IO package" }, { "code": null, "e": 27833, "s": 27828, "text": "Java" }, { "code": null, "e": 27838, "s": 27833, "text": "Java" }, { "code": null, "e": 27936, "s": 27838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27951, "s": 27936, "text": "Stream In Java" }, { "code": null, "e": 27970, "s": 27951, "text": "Exceptions in Java" }, { "code": null, "e": 27991, "s": 27970, "text": "Constructors in Java" }, { "code": null, "e": 28021, "s": 27991, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28067, "s": 28021, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28084, "s": 28067, "text": "Generics in Java" }, { "code": null, "e": 28105, "s": 28084, "text": "Introduction to Java" }, { "code": null, "e": 28148, "s": 28105, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28170, "s": 28148, "text": "PriorityQueue in Java" } ]
Matplotlib - Working With Text
Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm. The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands. The following list of commands are used to create text in the Pyplot interface − All of these functions create and return a matplotlib.text.Text() instance. Following scripts demonstrate the use of some of the above functions − import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.set_title('axes title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') ax.text(3, 8, 'boxed italics text in data coords', style='italic', bbox = {'facecolor': 'red'}) ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 15) ax.text(4, 0.05, 'colored text in axes coords', verticalalignment = 'bottom', color = 'green', fontsize = 15) ax.plot([2], [1], 'o') ax.annotate('annotate', xy = (2, 1), xytext = (3, 4), arrowprops = dict(facecolor = 'black', shrink = 0.05)) ax.axis([0, 10, 0, 10]) plt.show() The above line of code will generate the following output − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2846, "s": 2516, "text": "Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm." }, { "code": null, "e": 3032, "s": 2846, "text": "The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands." }, { "code": null, "e": 3113, "s": 3032, "text": "The following list of commands are used to create text in the Pyplot interface −" }, { "code": null, "e": 3189, "s": 3113, "text": "All of these functions create and return a matplotlib.text.Text() instance." }, { "code": null, "e": 3260, "s": 3189, "text": "Following scripts demonstrate the use of some of the above functions −" }, { "code": null, "e": 3848, "s": 3260, "text": "import matplotlib.pyplot as plt\nfig = plt.figure()\n\nax = fig.add_axes([0,0,1,1])\n\nax.set_title('axes title')\nax.set_xlabel('xlabel')\nax.set_ylabel('ylabel')\nax.text(3, 8, 'boxed italics text in data coords', style='italic', \nbbox = {'facecolor': 'red'})\nax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 15)\nax.text(4, 0.05, 'colored text in axes coords',\nverticalalignment = 'bottom', color = 'green', fontsize = 15)\nax.plot([2], [1], 'o')\nax.annotate('annotate', xy = (2, 1), xytext = (3, 4),\narrowprops = dict(facecolor = 'black', shrink = 0.05))\nax.axis([0, 10, 0, 10])\nplt.show()" }, { "code": null, "e": 3908, "s": 3848, "text": "The above line of code will generate the following output −" }, { "code": null, "e": 3941, "s": 3908, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3958, "s": 3941, "text": " Abhilash Nelson" }, { "code": null, "e": 3991, "s": 3958, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 4026, "s": 3991, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4060, "s": 4026, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4095, "s": 4060, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4128, "s": 4095, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 4138, "s": 4128, "text": " Aipython" }, { "code": null, "e": 4173, "s": 4138, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4185, "s": 4173, "text": " Akbar Khan" }, { "code": null, "e": 4218, "s": 4185, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4225, "s": 4218, "text": " Anmol" }, { "code": null, "e": 4232, "s": 4225, "text": " Print" }, { "code": null, "e": 4243, "s": 4232, "text": " Add Notes" } ]
Interfacing ESP32 with Analog Sensors
Another important category of sensors that you need to interface with ESP32 is analog sensors. There are many types of analog sensors, LDRs (Light Dependent Resistors), current and voltage sensors being popular examples. Now, if you are familiar with how analogRead works on any Arduino board, like Arduino Uno, then this chapter will be a cakewalk for you because ESP32 uses the same functions. There are only a few nuances you should be aware of, that will be covered in this chapter. Every microcontroller which supports ADC will have a defined resolution and a reference voltage. The reference voltage is generally the supply voltage. The analog voltage provided to the ADC pin should be less than or equal to the reference voltage. The resolution indicates the number of bits that will be used to represent the digital value. Thus, if the resolution is 8 bits, then the value will be represented by 8 bits, and the maximum value possible is 255. This maximum value corresponds to the value of the reference voltage. The values for other voltages are often derived by scaling. Thus, if the reference voltage is 5V and an 8−bit ADC is used, then 5V corresponds to a reading of 255, 1V corresponds to a reading of (255/5*1) = 51, 2V corresponds to a reading (255/5*2) = 102 and so on. If we had a 12 bit ADC, then 5V would correspond to a reading of 4095, 1V would correspond to a reading of (4095/5*1) = 819, and so on. The reverse calculations can be performed similarly. If you get a value of 1000 on a 12 bit ADC with a reference voltage of 3.3V, then it corresponds to a value of (1000/4095*3.3) = 0.8V approximately. If you get a reading of 825 on a 10 bit ADC with a reference voltage of 5V, it corresponds to a value of (825/1023*5) = 4.03V approximately. With the above explanation, it will be clear that both the reference voltage and the number of bits used for ADC determine the minimum possible voltage change that can be detected. If the reference voltage is 5V and the resolution is 12-bit, you have 4095 values to represent a voltage range of 0−5V. Thus, the minimum change that can be detected is 5V/4095 = 1.2mV. Similarly, for a 5V and 8-bit reference voltage, you have only 255 values to represent a range of 0-5V. Thus, the minimum change that can be detected is 5V/255 = 19.6mV, or about 16 times higher than the minimum change detected with a 12-bit resolution. Considering the popularity and availability of the sensor, we will use an LDR for the demonstration. We will essentially connect LDR in series with a regular resistor, and feed the voltage at the point connecting the two resistors to the ADC pin of ESP32. Which pin? Well, there are lots of them. ESP32 boasts of 18 ADC pins (8 in channel 1 and 10 in channel 2). However, channel 2 pins cannot be used along with WiFi. And some pins of channel 1 are not exposed on some boards. Therefore, I generally stick to the following 6 pins for ADC− 32, 33, 34, 35, 36, 39. In the image shown below, an LDR with a resistance of 90K is connected to a resistor of resistance 150K. The free end of the LDR is connected to the 3.3V pin of ESP32 and the free end of the resistor is connected to GND. The common end of the LDR and the resistor is fed to the ADC pin 36 (VN) of ESP32. GitHub link − https://github.com/ The code here is straightforward. No libraries need to be included. We just define the LDR pin as a constant, initialize serial in the setup(), and set the resolution of the ADC. Here we have set a resolution of 10-bits (meaning the maximum value is 1023). By default the resolution is 12-bits and for ESP32, the minimum possible resolution is 9 bits. const int LDR_PIN = 36; void setup() { // put your setup code here, to run once: Serial.begin(115200); analogReadResolution(10); //default is 12. Can be set between 9-12. } In the loop, we just read the value from the LDR pin and print it to the serial monitor. Also, we convert it to voltage and print the corresponding voltage as well. void loop() { // put your main code here, to run repeatedly: // LDR Resistance: 90k ohms // Resistance in series: 150k ohms // Pinouts: // Vcc −> 3.3 (CONNECTED TO LDR FREE END) // Gnd −> Gnd (CONNECTED TO RESISTOR FREE END) // Analog Read −> Vp (36) − Intermediate between LDR and resistance. int LDR_Reading = analogRead(LDR_PIN); float LDR_Voltage = ((float)LDR_Reading*3.3/1023); Serial.print("Reading: ");Serial.print(LDR_Reading); Serial.print("\t");Serial.print("Voltage: ");Serial.println(LDR_Voltage); } We have used 1023 as the divisor because we have set the ADC resolution to 10 bits. In case you change the ADC value to N, you need to change the divisor to (2^N −1). Now place your hand on the LDR We have used 1023 as the divisor because we have set the ADC resolution to 10 bits. In case you change the ADC value to N, you need to change the divisor to (2^N −1). Now place your hand on the LDR, and see the effect on the voltage, and then flash a torch on the LDR and see the voltage swing to the opposite extreme on the Serial Monitor. That's it. You've successfully captured data from an analog sensor on ESP32. Analog to Digital Converted on ESP32 Analog to Digital Converted on ESP32 54 Lectures 4.5 hours Frahaan Hussain 20 Lectures 5 hours Azaz Patel 20 Lectures 4 hours Azaz Patel 0 Lectures 0 mins Eduonix Learning Solutions 169 Lectures 12.5 hours Kalob Taulien 29 Lectures 2 hours Zenva Print Add Notes Bookmark this page
[ { "code": null, "e": 2672, "s": 2183, "text": "Another important category of sensors that you need to interface with ESP32 is analog sensors. There are many types of analog sensors, LDRs (Light Dependent Resistors), current and voltage sensors being popular examples. Now, \nif you are familiar with how analogRead works on any Arduino board, like Arduino Uno, then this chapter will be a cakewalk for you because ESP32 uses the same functions. There are only a few nuances you should be aware of, that will be covered in this chapter. " }, { "code": null, "e": 3267, "s": 2672, "text": "Every microcontroller which supports ADC will have a defined resolution and a reference voltage. The reference voltage is generally the supply voltage. The analog voltage provided to the ADC pin should be less than or equal to the reference voltage. The resolution indicates the number of bits that will be used to represent the digital value. Thus, if the resolution is 8 bits, then the value will be represented by 8 bits, and the maximum value possible is 255. This maximum value corresponds to the value of the reference voltage. The values for other voltages are often derived by scaling. " }, { "code": null, "e": 3609, "s": 3267, "text": "Thus, if the reference voltage is 5V and an 8−bit ADC is used, then 5V corresponds to a reading of 255, 1V corresponds to a reading of (255/5*1) = 51, 2V corresponds to a reading (255/5*2) = 102 and so on. If we had a 12 bit ADC, then 5V would correspond to a reading of 4095, 1V would correspond to\na reading of (4095/5*1) = 819, and so on." }, { "code": null, "e": 3953, "s": 3609, "text": " The reverse calculations can be performed similarly. If you get a value of 1000 on a 12 bit ADC with a reference voltage of 3.3V, then it corresponds to a value of (1000/4095*3.3) = 0.8V approximately. If you get a reading of 825 on a 10 bit ADC with a reference voltage of 5V, it corresponds to a value of (825/1023*5) = 4.03V approximately." }, { "code": null, "e": 4574, "s": 3953, "text": "With the above explanation, it will be clear that both the reference voltage and the number of bits used for ADC determine the minimum possible voltage change that can be detected. If the reference voltage is 5V and the resolution is 12-bit, you have 4095 values to represent a voltage range of 0−5V. Thus, the minimum change that can be detected is 5V/4095 = 1.2mV. Similarly, for a 5V and 8-bit reference voltage, you have only 255 values to represent a range of 0-5V. Thus, the minimum change that can be detected is 5V/255 = 19.6mV, or about 16 times higher than the minimum change detected with a 12-bit resolution." }, { "code": null, "e": 5442, "s": 4574, "text": "Considering the popularity and availability of the sensor, we will use an LDR for the demonstration. We will essentially connect LDR in series with a regular resistor, and feed the voltage at the point connecting the two resistors to the ADC pin of ESP32. Which pin? Well, there are lots of them. ESP32 boasts of 18 ADC pins (8 in channel 1 and 10 in channel 2). However, channel 2 pins cannot be used along with WiFi. And some pins of channel 1 are not exposed on some boards.\nTherefore, I generally stick to the following 6 pins for ADC− 32, 33, 34, 35, 36, 39. In the image shown below, an LDR with a resistance of 90K is connected to a resistor of resistance 150K. The free end of the LDR is connected to the 3.3V pin of ESP32 and the free end of the resistor is connected to GND. The common end of the LDR and the resistor is fed to the ADC pin 36 (VN) of ESP32." }, { "code": null, "e": 5476, "s": 5442, "text": "GitHub link − https://github.com/" }, { "code": null, "e": 5829, "s": 5476, "text": "The code here is straightforward. No libraries need to be included. We just define the LDR pin as a constant, initialize serial in the setup(), and set the resolution of the ADC. Here we have set a resolution of 10-bits (meaning the maximum value is 1023). By default the resolution is 12-bits and for ESP32, the minimum possible resolution is 9 bits. " }, { "code": null, "e": 6013, "s": 5829, "text": "const int LDR_PIN = 36;\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(115200);\n analogReadResolution(10); //default is 12. Can be set between 9-12.\n}\n" }, { "code": null, "e": 6178, "s": 6013, "text": "In the loop, we just read the value from the LDR pin and print it to the serial monitor. Also, we convert it to voltage and print the corresponding voltage as well." }, { "code": null, "e": 6722, "s": 6178, "text": "void loop() {\n // put your main code here, to run repeatedly:\n // LDR Resistance: 90k ohms\n // Resistance in series: 150k ohms\n // Pinouts:\n // Vcc −> 3.3 (CONNECTED TO LDR FREE END)\n // Gnd −> Gnd (CONNECTED TO RESISTOR FREE END)\n // Analog Read −> Vp (36) − Intermediate between LDR and resistance. \n int LDR_Reading = analogRead(LDR_PIN);\n float LDR_Voltage = ((float)LDR_Reading*3.3/1023);\n Serial.print(\"Reading: \");Serial.print(LDR_Reading); Serial.print(\"\\t\");Serial.print(\"Voltage: \");Serial.println(LDR_Voltage);\n}" }, { "code": null, "e": 6921, "s": 6722, "text": "We have used 1023 as the divisor because we have set the ADC resolution to 10 bits. In case you change the ADC value to N, you need to change the divisor to (2^N −1). Now place your hand on the LDR " }, { "code": null, "e": 7339, "s": 6921, "text": "We have used 1023 as the divisor because we have set the ADC resolution to 10 bits. In case you change the ADC value to N, you need to change the divisor to (2^N −1). Now place your hand on the LDR, and see the effect on the voltage, and then flash a torch on the LDR and see the voltage swing to the opposite extreme on the Serial Monitor. That's it. You've successfully captured data from an analog\nsensor on ESP32." }, { "code": null, "e": 7376, "s": 7339, "text": "Analog to Digital Converted on ESP32" }, { "code": null, "e": 7413, "s": 7376, "text": "Analog to Digital Converted on ESP32" }, { "code": null, "e": 7448, "s": 7413, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7465, "s": 7448, "text": " Frahaan Hussain" }, { "code": null, "e": 7498, "s": 7465, "text": "\n 20 Lectures \n 5 hours \n" }, { "code": null, "e": 7510, "s": 7498, "text": " Azaz Patel" }, { "code": null, "e": 7543, "s": 7510, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 7555, "s": 7543, "text": " Azaz Patel" }, { "code": null, "e": 7585, "s": 7555, "text": "\n 0 Lectures \n 0 mins\n" }, { "code": null, "e": 7613, "s": 7585, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7650, "s": 7613, "text": "\n 169 Lectures \n 12.5 hours \n" }, { "code": null, "e": 7665, "s": 7650, "text": " Kalob Taulien" }, { "code": null, "e": 7698, "s": 7665, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 7705, "s": 7698, "text": " Zenva" }, { "code": null, "e": 7712, "s": 7705, "text": " Print" }, { "code": null, "e": 7723, "s": 7712, "text": " Add Notes" } ]
K nearest neighbors, it’s purpose and how to use it | by Robert Miller | Towards Data Science
For those of you who don’t know what k nearest neighbors is, it is a predictive model. Whats its purpose, why use it? Those are the questions we will delve into in this post. In order for this model to work the data must have a notion of distance. In laymens terms, we need to be able to graph our data. This model will is non-linear and can be used on classes. What I mean by classes is it can help determine if a data point will be part of one class or another. A good example is determining if someone will be a republican or democrat based on their income and age. This model will prove useful because in essence it looks at the neighboring data points to determine what this new data point will fall into. Now that we know why this is useful, lets give an example with how to do this in python. This example will be using pedal width, pedal length, sepal length, and sepal width to try to determine the classification of flower import pandas as pdurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']iris = pd.read_csv(url, header=None, names=col_names) Firstly, I imported pandas (a python library) and then read in my dataset and set column names. This puts my data into a nice dataframe that can easily be analyzed. from matplotlib.colors import ListedColormapcmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'] The chunk of code above imports color graphing ability . iris["Species_number"] = iris.species.map({'Iris-setosa':0,'Iris-versicolor':1,'Iris-virginica':2 }) I then made a new column mapping each species to a different bin, the bins being 0,1, or 2. iris.plot(kind = 'scatter', x = "petal_length", y = "petal_width", c ="Species_number" ,colormap= cmap_bold ) This shows pedal width and petal length to determine the species. The species each being a different color. feature_cols = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] X = iris[feature_cols]y = iris.Species_number This Makes our X the sepal length, sepal width, petal length, petal width. Our Y is the species column with three bins. We are trying to use X features to determine Y from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y) For any good model you will want to do a train test split to avoid over fitting your model. What this does is takes your data and splits in to a training set, and then a testing set to test how well your model is. K nearest neighbors (also knows as KNN) is a lazy model, this means is that it does not use the training data points to do any generalization. So we are not going to train a model. Then why train test split you might ask? Because we still need that testing set to test on the 70% to see if our X variables are good predictors. from sklearn.neighbors import KNeighborsClassifierfrom sklearn import metrics# make an instance of a KNeighborsClassifier objectknn = KNeighborsClassifier(n_neighbors=1)knn.fit(X_train, y_train) We then import from sklearn.neighbors to be able to use our KNN model. Using KNeighborsClassifier and then the argument inside determines how many nearest neighbors you want your datapoint to look at. There is no rule of thumb for how many neighbors you should look at. The best way to find out how many neighbors to look at is to test a range of neighbors and determine what has the best accuracy. y_pred_class = knn.predict(X_test)print metrics.accuracy_score(y_test, y_pred_class) This will let you see the accuracy score, and since we only had 1 nearest neighbor to check, our score ended up being a 1 (also know as 100%), which has potential to be overfit. def length(X, y): empty_list = [] for n in range(1,100): X_train, X_test, y_train, y_test = train_test_split(X, y) knn = KNeighborsClassifier(n_neighbors=(n)) knn.fit(X_train, y_train) y_pred_class = knn.predict(X_test) empty_list.append(metrics.accuracy_score(y_test, y_pred_class)) return empty_list This function will test 1–100 nearest neighbors and return the accuracy for each. This will help you look for the best number of neighbors to look at for your model Once you determine the Best neighbor you can use your model on other data points to put them into a class. Thats how you use KNN, I hope this helped those of you interested in predicting what classes data points will fall into
[ { "code": null, "e": 221, "s": 46, "text": "For those of you who don’t know what k nearest neighbors is, it is a predictive model. Whats its purpose, why use it? Those are the questions we will delve into in this post." }, { "code": null, "e": 350, "s": 221, "text": "In order for this model to work the data must have a notion of distance. In laymens terms, we need to be able to graph our data." }, { "code": null, "e": 757, "s": 350, "text": "This model will is non-linear and can be used on classes. What I mean by classes is it can help determine if a data point will be part of one class or another. A good example is determining if someone will be a republican or democrat based on their income and age. This model will prove useful because in essence it looks at the neighboring data points to determine what this new data point will fall into." }, { "code": null, "e": 846, "s": 757, "text": "Now that we know why this is useful, lets give an example with how to do this in python." }, { "code": null, "e": 979, "s": 846, "text": "This example will be using pedal width, pedal length, sepal length, and sepal width to try to determine the classification of flower" }, { "code": null, "e": 1216, "s": 979, "text": "import pandas as pdurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']iris = pd.read_csv(url, header=None, names=col_names)" }, { "code": null, "e": 1381, "s": 1216, "text": "Firstly, I imported pandas (a python library) and then read in my dataset and set column names. This puts my data into a nice dataframe that can easily be analyzed." }, { "code": null, "e": 1486, "s": 1381, "text": "from matplotlib.colors import ListedColormapcmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']" }, { "code": null, "e": 1543, "s": 1486, "text": "The chunk of code above imports color graphing ability ." }, { "code": null, "e": 1644, "s": 1543, "text": "iris[\"Species_number\"] = iris.species.map({'Iris-setosa':0,'Iris-versicolor':1,'Iris-virginica':2 })" }, { "code": null, "e": 1736, "s": 1644, "text": "I then made a new column mapping each species to a different bin, the bins being 0,1, or 2." }, { "code": null, "e": 1846, "s": 1736, "text": "iris.plot(kind = 'scatter', x = \"petal_length\", y = \"petal_width\", c =\"Species_number\" ,colormap= cmap_bold )" }, { "code": null, "e": 1954, "s": 1846, "text": "This shows pedal width and petal length to determine the species. The species each being a different color." }, { "code": null, "e": 2078, "s": 1954, "text": "feature_cols = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] X = iris[feature_cols]y = iris.Species_number" }, { "code": null, "e": 2245, "s": 2078, "text": "This Makes our X the sepal length, sepal width, petal length, petal width. Our Y is the species column with three bins. We are trying to use X features to determine Y" }, { "code": null, "e": 2355, "s": 2245, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y)" }, { "code": null, "e": 2896, "s": 2355, "text": "For any good model you will want to do a train test split to avoid over fitting your model. What this does is takes your data and splits in to a training set, and then a testing set to test how well your model is. K nearest neighbors (also knows as KNN) is a lazy model, this means is that it does not use the training data points to do any generalization. So we are not going to train a model. Then why train test split you might ask? Because we still need that testing set to test on the 70% to see if our X variables are good predictors." }, { "code": null, "e": 3091, "s": 2896, "text": "from sklearn.neighbors import KNeighborsClassifierfrom sklearn import metrics# make an instance of a KNeighborsClassifier objectknn = KNeighborsClassifier(n_neighbors=1)knn.fit(X_train, y_train)" }, { "code": null, "e": 3490, "s": 3091, "text": "We then import from sklearn.neighbors to be able to use our KNN model. Using KNeighborsClassifier and then the argument inside determines how many nearest neighbors you want your datapoint to look at. There is no rule of thumb for how many neighbors you should look at. The best way to find out how many neighbors to look at is to test a range of neighbors and determine what has the best accuracy." }, { "code": null, "e": 3575, "s": 3490, "text": "y_pred_class = knn.predict(X_test)print metrics.accuracy_score(y_test, y_pred_class)" }, { "code": null, "e": 3753, "s": 3575, "text": "This will let you see the accuracy score, and since we only had 1 nearest neighbor to check, our score ended up being a 1 (also know as 100%), which has potential to be overfit." }, { "code": null, "e": 4099, "s": 3753, "text": "def length(X, y): empty_list = [] for n in range(1,100): X_train, X_test, y_train, y_test = train_test_split(X, y) knn = KNeighborsClassifier(n_neighbors=(n)) knn.fit(X_train, y_train) y_pred_class = knn.predict(X_test) empty_list.append(metrics.accuracy_score(y_test, y_pred_class)) return empty_list" }, { "code": null, "e": 4264, "s": 4099, "text": "This function will test 1–100 nearest neighbors and return the accuracy for each. This will help you look for the best number of neighbors to look at for your model" }, { "code": null, "e": 4371, "s": 4264, "text": "Once you determine the Best neighbor you can use your model on other data points to put them into a class." } ]
numpy.char.split()
This function returns a list of words in the input string. By default, a whitespace is used as a separator. Otherwise the specified separator character is used to spilt the string. import numpy as np print np.char.split ('hello how are you?') print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',') Its output would be − ['hello', 'how', 'are', 'you?'] ['TutorialsPoint', 'Hyderabad', 'Telangana'] 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2424, "s": 2243, "text": "This function returns a list of words in the input string. By default, a whitespace is used as a separator. Otherwise the specified separator character is used to spilt the string." }, { "code": null, "e": 2558, "s": 2424, "text": "import numpy as np \nprint np.char.split ('hello how are you?') \nprint np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')" }, { "code": null, "e": 2580, "s": 2558, "text": "Its output would be −" }, { "code": null, "e": 2658, "s": 2580, "text": "['hello', 'how', 'are', 'you?']\n['TutorialsPoint', 'Hyderabad', 'Telangana']\n" }, { "code": null, "e": 2691, "s": 2658, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2708, "s": 2691, "text": " Abhilash Nelson" }, { "code": null, "e": 2741, "s": 2708, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 2776, "s": 2741, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2809, "s": 2776, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 2844, "s": 2809, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2879, "s": 2844, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2891, "s": 2879, "text": " Akbar Khan" }, { "code": null, "e": 2924, "s": 2891, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 2939, "s": 2924, "text": " Pruthviraja L" }, { "code": null, "e": 2972, "s": 2939, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2979, "s": 2972, "text": " Anmol" }, { "code": null, "e": 2986, "s": 2979, "text": " Print" }, { "code": null, "e": 2997, "s": 2986, "text": " Add Notes" } ]
sigaction() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP. If act is non-null, the new action for signal signum is installed from act. If oldact is non-null, the previous action is saved in oldact. The sigaction structure is defined as something like struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer)(void); } On some architectures a union is involved: do not assign to both sa_handler and sa_sigaction. The sa_restorer element is obsolete and should not be used. POSIX does not specify a sa_restorer element. sa_handler specifies the action to be associated with signum and may be SIG_DFL for the default action, SIG_IGN to ignore this signal, or a pointer to a signal handling function. This function receives the signal number as its only argument. If SA_SIGINFO is specified in sa_flags, then sa_sigaction (instead of sa_handler) specifies the signal-handling function for signum. This function receives the signal number as its first argument, a pointer to a siginfo_t as its second argument and a pointer to a ucontext_t (cast to void *) as its third argument. sa_mask gives a mask of signals which should be blocked during execution of the signal handler. In addition, the signal which triggered the handler will be blocked, unless the SA_NODEFER flag is used. sa_flags specifies a set of flags which modify the behaviour of the signal handling process. It is formed by the bitwise OR of zero or more of the following: The siginfo_t parameter to sa_sigaction is a struct with the following elements siginfo_t { int si_signo; /* Signal number */ int si_errno; /* An errno value */ int si_code; /* Signal code */ pid_t si_pid; /* Sending process ID */ uid_t si_uid; /* Real user ID of sending process */ int si_status; /* Exit value or signal */ clock_t si_utime; /* User time consumed */ clock_t si_stime; /* System time consumed */ sigval_t si_value; /* Signal value */ int si_int; /* POSIX.1b signal */ void * si_ptr; /* POSIX.1b signal */ void * si_addr; /* Memory location which caused fault */ int si_band; /* Band event */ int si_fd; /* File descriptor */ } si_signo, si_errno and si_code are defined for all signals. (si_signo is unused on Linux.) The rest of the struct may be a union, so that one should only read the fields that are meaningful for the given signal. POSIX.1b signals and SIGCHLD fill in si_pid and si_uid. SIGCHLD also fills in si_status, si_utime and si_stime. si_int and si_ptr are specified by the sender of the POSIX.1b signal. SIGILL, SIGFPE, SIGSEGV, and SIGBUS fill in si_addr with the address of the fault. SIGPOLL fills in si_band and si_fd. si_code indicates why this signal was sent. It is a value, not a bitmask. The values which are possible for any signal are listed in this table: According to POSIX, the behaviour of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill() or raise(). Integer division by zero has undefined result. On some architectures it will generate a SIGFPE signal. (Also dividing the most negative integer by -1 may generate SIGFPE.) Ignoring this signal might lead to an endless loop. POSIX.1-1990 disallowed setting the action for SIGCHLD to SIG_IGN. POSIX.1-2001 allows this possibility, so that ignoring SIGCHLD can be used to prevent the creation of zombies (see wait(2)). Nevertheless, the historical BSD and System V behaviours for ignoring SIGCHLD differ, so that the only completely portable method of ensuring that terminated children do not become zombies is to catch the SIGCHLD signal and perform a wait(2) or similar. POSIX.1-1990 only specified SA_NOCLDSTOP. POSIX.1-2001 added SA_NOCLDWAIT, SA_RESETHAND, SA_NODEFER, and SA_SIGINFO. Use of these latter values in sa_flags may be less portable in applications intended for older Unix implementations. Support for SA_SIGINFO was added in Linux 2.2. The SA_RESETHAND flag is compatible with the SVr4 flag of the same name. The SA_NODEFER flag is compatible with the SVr4 flag of the same name under kernels 1.3.9 and newer. On older kernels the Linux implementation allowed the receipt of any signal, not just the one we are installing (effectively overriding any sa_mask settings). sigaction() can be called with a null second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with null second and third arguments. It is not possible to block SIGKILL or SIGSTOP (by specifying them in sa_mask). Attempts to do so are silently ignored. See sigsetops(3) for details on manipulating signal sets. kill (1) kill (1) kill (2) kill (2) pause (2) pause (2) sigaltstack (2) sigaltstack (2) signal (2) signal (2) sigpending (2) sigpending (2) sigprocmask (2) sigprocmask (2) sigqueue (2) sigqueue (2) sigsuspend (2) sigsuspend (2) wait (2) wait (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2403, "s": 2319, "text": "\nint sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); " }, { "code": null, "e": 2489, "s": 2403, "text": "\nsignum specifies the signal and can be any valid signal except\nSIGKILL and\nSIGSTOP. " }, { "code": null, "e": 2630, "s": 2489, "text": "\nIf\nact is non-null, the new action for signal\nsignum is installed from\nact. If\noldact is non-null, the previous action is saved in\noldact. " }, { "code": null, "e": 2685, "s": 2630, "text": "\nThe\nsigaction structure is defined as something like\n" }, { "code": null, "e": 2861, "s": 2687, "text": "struct sigaction {\n void (*sa_handler)(int);\n void (*sa_sigaction)(int, siginfo_t *, void *);\n sigset_t sa_mask;\n int sa_flags;\n void (*sa_restorer)(void);\n}\n" }, { "code": null, "e": 2957, "s": 2861, "text": "\nOn some architectures a union is involved: do not assign to both\nsa_handler and\nsa_sigaction. " }, { "code": null, "e": 3065, "s": 2957, "text": "\nThe\nsa_restorer element is obsolete and should not be used.\nPOSIX does not specify a\nsa_restorer element.\n" }, { "code": null, "e": 3309, "s": 3065, "text": "\nsa_handler specifies the action to be associated with\nsignum and may be\nSIG_DFL for the default action,\nSIG_IGN to ignore this signal, or a pointer to a signal handling function.\nThis function receives the signal number as its only argument.\n" }, { "code": null, "e": 3626, "s": 3309, "text": "\nIf\nSA_SIGINFO is specified in\nsa_flags, then\nsa_sigaction (instead of\nsa_handler) specifies the signal-handling function for\nsignum. This function receives the signal number as its first argument, a\npointer to a\nsiginfo_t as its second argument and a pointer to a\nucontext_t (cast to void *) as its third argument.\n" }, { "code": null, "e": 3830, "s": 3626, "text": "\nsa_mask gives a mask of signals which should be blocked during execution of\nthe signal handler. In addition, the signal which triggered the handler\nwill be blocked, unless the\nSA_NODEFER flag is used.\n" }, { "code": null, "e": 3990, "s": 3830, "text": "\nsa_flags specifies a set of flags which modify the behaviour of the signal handling\nprocess. It is formed by the bitwise OR of zero or more of the following:\n" }, { "code": null, "e": 4072, "s": 3990, "text": "\nThe\nsiginfo_t parameter to\nsa_sigaction is a struct with the following elements\n" }, { "code": null, "e": 4769, "s": 4074, "text": "siginfo_t {\n int si_signo; /* Signal number */\n int si_errno; /* An errno value */\n int si_code; /* Signal code */\n pid_t si_pid; /* Sending process ID */\n uid_t si_uid; /* Real user ID of sending process */\n int si_status; /* Exit value or signal */\n clock_t si_utime; /* User time consumed */\n clock_t si_stime; /* System time consumed */\n sigval_t si_value; /* Signal value */\n int si_int; /* POSIX.1b signal */\n void * si_ptr; /* POSIX.1b signal */\n void * si_addr; /* Memory location which caused fault */\n int si_band; /* Band event */\n int si_fd; /* File descriptor */\n}\n" }, { "code": null, "e": 5285, "s": 4769, "text": "\nsi_signo, si_errno and si_code are defined for all signals.\n(si_signo is unused on Linux.)\nThe rest of the struct may be a union, so that one should only\nread the fields that are meaningful for the given signal.\nPOSIX.1b signals and\nSIGCHLD fill in\nsi_pid and si_uid. SIGCHLD also fills in\nsi_status, si_utime and si_stime. si_int and si_ptr are specified by the sender of the POSIX.1b signal.\nSIGILL, SIGFPE, SIGSEGV, and\nSIGBUS fill in\nsi_addr with the address of the fault.\nSIGPOLL fills in\nsi_band and si_fd. " }, { "code": null, "e": 5434, "s": 5285, "text": "\nsi_code indicates why this signal was sent. It is a value, not a bitmask. The\nvalues which are possible for any signal are listed in this table:\n" }, { "code": null, "e": 5834, "s": 5450, "text": "\nAccording to POSIX, the behaviour of a process is undefined after it\nignores a\nSIGFPE, SIGILL, or\nSIGSEGV signal that was not generated by\nkill() or\nraise(). Integer division by zero has undefined result.\nOn some architectures it will generate a\nSIGFPE signal.\n(Also dividing the most negative integer by -1 may generate SIGFPE.)\nIgnoring this signal might lead to an endless loop.\n" }, { "code": null, "e": 6282, "s": 5834, "text": "\nPOSIX.1-1990 disallowed setting the action for\nSIGCHLD to\nSIG_IGN. POSIX.1-2001 allows this possibility, so that ignoring\nSIGCHLD can be used to prevent the creation of zombies (see\nwait(2)).\nNevertheless, the historical BSD and System V behaviours for ignoring\nSIGCHLD differ, so that the only completely portable method of ensuring that\nterminated children do not become zombies is to catch the\nSIGCHLD signal and perform a\nwait(2)\nor similar.\n" }, { "code": null, "e": 6518, "s": 6282, "text": "\nPOSIX.1-1990 only specified\nSA_NOCLDSTOP. POSIX.1-2001 added\nSA_NOCLDWAIT, SA_RESETHAND, SA_NODEFER, and\nSA_SIGINFO. Use of these latter values in\nsa_flags may be less portable in applications intended for older\nUnix implementations.\n" }, { "code": null, "e": 6567, "s": 6518, "text": "\nSupport for\nSA_SIGINFO was added in Linux 2.2.\n" }, { "code": null, "e": 6642, "s": 6567, "text": "\nThe\nSA_RESETHAND flag is compatible with the SVr4 flag of the same name.\n" }, { "code": null, "e": 6905, "s": 6642, "text": "\nThe\nSA_NODEFER flag is compatible with the SVr4 flag of the same name under kernels\n1.3.9 and newer. On older kernels the Linux implementation\nallowed the receipt of any signal, not just the one we are installing\n(effectively overriding any\nsa_mask settings).\n" }, { "code": null, "e": 7135, "s": 6905, "text": "\nsigaction() can be called with a null second argument to query the current signal\nhandler. It can also be used to check whether a given signal is valid for\nthe current machine by calling it with null second and third arguments.\n" }, { "code": null, "e": 7257, "s": 7135, "text": "\nIt is not possible to block\nSIGKILL or SIGSTOP (by specifying them in\nsa_mask). Attempts to do so are silently ignored.\n" }, { "code": null, "e": 7317, "s": 7257, "text": "\nSee\nsigsetops(3)\nfor details on manipulating signal sets.\n" }, { "code": null, "e": 7326, "s": 7317, "text": "kill (1)" }, { "code": null, "e": 7335, "s": 7326, "text": "kill (1)" }, { "code": null, "e": 7344, "s": 7335, "text": "kill (2)" }, { "code": null, "e": 7353, "s": 7344, "text": "kill (2)" }, { "code": null, "e": 7363, "s": 7353, "text": "pause (2)" }, { "code": null, "e": 7373, "s": 7363, "text": "pause (2)" }, { "code": null, "e": 7389, "s": 7373, "text": "sigaltstack (2)" }, { "code": null, "e": 7405, "s": 7389, "text": "sigaltstack (2)" }, { "code": null, "e": 7416, "s": 7405, "text": "signal (2)" }, { "code": null, "e": 7427, "s": 7416, "text": "signal (2)" }, { "code": null, "e": 7442, "s": 7427, "text": "sigpending (2)" }, { "code": null, "e": 7457, "s": 7442, "text": "sigpending (2)" }, { "code": null, "e": 7473, "s": 7457, "text": "sigprocmask (2)" }, { "code": null, "e": 7489, "s": 7473, "text": "sigprocmask (2)" }, { "code": null, "e": 7502, "s": 7489, "text": "sigqueue (2)" }, { "code": null, "e": 7515, "s": 7502, "text": "sigqueue (2)" }, { "code": null, "e": 7530, "s": 7515, "text": "sigsuspend (2)" }, { "code": null, "e": 7545, "s": 7530, "text": "sigsuspend (2)" }, { "code": null, "e": 7554, "s": 7545, "text": "wait (2)" }, { "code": null, "e": 7563, "s": 7554, "text": "wait (2)" }, { "code": null, "e": 7580, "s": 7563, "text": "\nAdvertisements\n" }, { "code": null, "e": 7615, "s": 7580, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 7643, "s": 7615, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7677, "s": 7643, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7694, "s": 7677, "text": " Frahaan Hussain" }, { "code": null, "e": 7727, "s": 7694, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 7738, "s": 7727, "text": " Pradeep D" }, { "code": null, "e": 7773, "s": 7738, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7789, "s": 7773, "text": " Musab Zayadneh" }, { "code": null, "e": 7822, "s": 7789, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 7834, "s": 7822, "text": " GUHARAJANM" }, { "code": null, "e": 7866, "s": 7834, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 7874, "s": 7866, "text": " Uplatz" }, { "code": null, "e": 7881, "s": 7874, "text": " Print" }, { "code": null, "e": 7892, "s": 7881, "text": " Add Notes" } ]
SQL | Query to select NAME from table using different options - GeeksforGeeks
19 Aug, 2020 Let us consider the following table named “Geeks” : SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME. Select FIRSTNAME AS NAME from Geeks; Output – SQL query to write “FIRSTNAME” from Geeks table in upper case. Select upper(FIRSTNAME) from Geeks; Output – SQL query to find the first three characters of FIRSTNAME from Geeks table. Select substring(FIRSTNAME, 1, 3) from Geeks; Output – SQL query to write the FIRSTNAME and LASTNAME from Geeks table into a single column COMPLETENAME with a space char should separate them. Select CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'COMPLETENAME' from Geeks; Output – Write an SQL query to print all Worker details from the Geeks table order by FIRSTNAME Ascending. Select * from Geeks order by FIRSTNAME asc; Output – DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views SQL Interview Questions SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
[ { "code": null, "e": 23891, "s": 23863, "text": "\n19 Aug, 2020" }, { "code": null, "e": 23943, "s": 23891, "text": "Let us consider the following table named “Geeks” :" }, { "code": null, "e": 24021, "s": 23943, "text": "SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME." }, { "code": null, "e": 24059, "s": 24021, "text": "Select FIRSTNAME AS NAME \nfrom Geeks;" }, { "code": null, "e": 24068, "s": 24059, "text": "Output –" }, { "code": null, "e": 24131, "s": 24068, "text": "SQL query to write “FIRSTNAME” from Geeks table in upper case." }, { "code": null, "e": 24168, "s": 24131, "text": "Select upper(FIRSTNAME) \nfrom Geeks;" }, { "code": null, "e": 24177, "s": 24168, "text": "Output –" }, { "code": null, "e": 24253, "s": 24177, "text": "SQL query to find the first three characters of FIRSTNAME from Geeks table." }, { "code": null, "e": 24300, "s": 24253, "text": "Select substring(FIRSTNAME, 1, 3) \nfrom Geeks;" }, { "code": null, "e": 24309, "s": 24300, "text": "Output –" }, { "code": null, "e": 24446, "s": 24309, "text": "SQL query to write the FIRSTNAME and LASTNAME from Geeks table into a single column COMPLETENAME with a space char should separate them." }, { "code": null, "e": 24517, "s": 24446, "text": "Select CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'COMPLETENAME' \nfrom Geeks;" }, { "code": null, "e": 24526, "s": 24517, "text": "Output –" }, { "code": null, "e": 24624, "s": 24526, "text": "Write an SQL query to print all Worker details from the Geeks table order by FIRSTNAME Ascending." }, { "code": null, "e": 24670, "s": 24624, "text": "Select * \nfrom Geeks \norder by FIRSTNAME asc;" }, { "code": null, "e": 24679, "s": 24670, "text": "Output –" }, { "code": null, "e": 24688, "s": 24679, "text": "DBMS-SQL" }, { "code": null, "e": 24692, "s": 24688, "text": "SQL" }, { "code": null, "e": 24696, "s": 24692, "text": "SQL" }, { "code": null, "e": 24794, "s": 24696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24805, "s": 24794, "text": "CTE in SQL" }, { "code": null, "e": 24871, "s": 24805, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 24883, "s": 24871, "text": "SQL | Views" }, { "code": null, "e": 24907, "s": 24883, "text": "SQL Interview Questions" }, { "code": null, "e": 24922, "s": 24907, "text": "SQL | GROUP BY" }, { "code": null, "e": 24961, "s": 24922, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25006, "s": 24961, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 25038, "s": 25006, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 25070, "s": 25038, "text": "What is Temporary Table in SQL?" } ]
Check which column names contain a specific string in R data frame.
If we have a data frame that contains columns having names with some commong strings then we might want to find those column names. For this purpose, we can use grepl function for subsetting along with colnames function. Check out the Examples given below to understand how it can be done. Following snippet creates a sample data frame − Students_Score<-sample(1:50,20) Teachers_Rank<-sample(1:5,20,replace=TRUE) Teachers_Score<-sample(1:50,20) df1<-data.frame(Students_Score,Teachers_Rank,Teachers_Score) df1 The following dataframe is created Students_Score Teachers_Rank Teachers_Score 1 20 5 8 2 28 1 26 3 42 2 49 4 25 2 11 5 7 4 19 6 4 5 37 7 48 1 9 8 33 4 35 9 23 5 38 10 31 3 29 11 43 1 6 12 6 4 13 13 15 5 33 14 9 1 40 15 41 3 43 16 11 4 34 17 46 5 42 18 44 1 5 19 21 3 48 20 29 4 15 To check columns of df1 that contains string Score on the above created data frame, add the following code to the above snippet − Students_Score<-sample(1:50,20) Teachers_Rank<-sample(1:5,20,replace=TRUE) Teachers_Score<-sample(1:50,20) df1<-data.frame(Students_Score,Teachers_Rank,Teachers_Score) colnames(df1)[grepl("Score",colnames(df1))] If you execute all the above given snippets as a single program, it generates the following Output − [1] "Students_Score" "Teachers_Score" Following snippet creates a sample data frame − Hot_Temp<-sample(33:50,20,replace=TRUE) Cold_Temp<-sample(1:10,20,replace=TRUE) Group<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(Hot_Temp,Cold_Temp,Group) df2 The following dataframe is created Hot_Temp Cold_Temp Group 1 47 7 First 2 38 5 Third 3 48 7 Third 4 36 10 First 5 46 6 Third 6 45 2 First 7 35 8 Second 8 33 1 Second 9 33 4 First 10 34 5 First 11 34 6 Third 12 39 10 Third 13 47 10 First 14 41 6 Third 15 48 3 First 16 36 2 Third 17 49 9 Second 18 35 5 Second 19 33 1 Second 20 49 10 Third To check columns of df2 that contains string Temp on the above created data frame, add the following code to the above snippet − Hot_Temp<-sample(33:50,20,replace=TRUE) Cold_Temp<-sample(1:10,20,replace=TRUE) Group<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(Hot_Temp,Cold_Temp,Group) colnames(df2)[grepl("Temp",colnames(df2))] If you execute all the above given snippets as a single program, it generates the following Output − [1] "Hot_Temp" "Cold_Temp" Following snippet creates a sample data frame − x1_Rate<-sample(1:10,20,replace=TRUE) x2_Rate<-sample(1:10,20,replace=TRUE) Category<-sample(c("Normal","Abnormal"),20,replace=TRUE) df3<-data.frame(x1_Rate,x2_Rate,Category) df3 The following dataframe is created x1_Rate x2_Rate Category 1 5 9 Normal 2 8 8 Normal 3 7 10 Normal 4 3 3 Normal 5 6 6 Normal 6 4 9 Abnormal 7 6 5 Abnormal 8 2 9 Abnormal 9 3 10 Abnormal 10 7 4 Abnormal 11 1 3 Normal 12 9 10 Abnormal 13 3 3 Normal 14 8 10 Abnormal 15 3 5 Normal 16 2 5 Abnormal 17 2 1 Normal 18 5 7 Abnormal 19 7 1 Abnormal 20 5 8 Normal To check columns of df3 that contains string Rate on the above created data frame, add the following code to the above snippet − x1_Rate<-sample(1:10,20,replace=TRUE) x2_Rate<-sample(1:10,20,replace=TRUE) Category<-sample(c("Normal","Abnormal"),20,replace=TRUE) df3<-data.frame(x1_Rate,x2_Rate,Category) colnames(df3)[grepl("Rate",colnames(df3))] If you execute all the above given snippets as a single program, it generates the following Output − [1] "x1_Rate" "x2_Rate"
[ { "code": null, "e": 1283, "s": 1062, "text": "If we have a data frame that contains columns having names with some commong\nstrings then we might want to find those column names. For this purpose, we can use\ngrepl function for subsetting along with colnames function." }, { "code": null, "e": 1352, "s": 1283, "text": "Check out the Examples given below to understand how it can be done." }, { "code": null, "e": 1400, "s": 1352, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1572, "s": 1400, "text": "Students_Score<-sample(1:50,20)\nTeachers_Rank<-sample(1:5,20,replace=TRUE)\nTeachers_Score<-sample(1:50,20)\ndf1<-data.frame(Students_Score,Teachers_Rank,Teachers_Score)\ndf1" }, { "code": null, "e": 1607, "s": 1572, "text": "The following dataframe is created" }, { "code": null, "e": 2459, "s": 1607, "text": " Students_Score Teachers_Rank Teachers_Score\n 1 20 5 8\n 2 28 1 26\n 3 42 2 49\n 4 25 2 11\n 5 7 4 19\n 6 4 5 37\n 7 48 1 9\n 8 33 4 35\n 9 23 5 38\n10 31 3 29\n11 43 1 6\n12 6 4 13\n13 15 5 33\n14 9 1 40\n15 41 3 43\n16 11 4 34\n17 46 5 42\n18 44 1 5\n19 21 3 48\n20 29 4 15" }, { "code": null, "e": 2589, "s": 2459, "text": "To check columns of df1 that contains string Score on the above created data frame, add\nthe following code to the above snippet −" }, { "code": null, "e": 2801, "s": 2589, "text": "Students_Score<-sample(1:50,20)\nTeachers_Rank<-sample(1:5,20,replace=TRUE)\nTeachers_Score<-sample(1:50,20)\ndf1<-data.frame(Students_Score,Teachers_Rank,Teachers_Score)\ncolnames(df1)[grepl(\"Score\",colnames(df1))]" }, { "code": null, "e": 2902, "s": 2801, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −" }, { "code": null, "e": 2941, "s": 2902, "text": "[1] \"Students_Score\" \"Teachers_Score\"\n" }, { "code": null, "e": 2989, "s": 2941, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 3174, "s": 2989, "text": "Hot_Temp<-sample(33:50,20,replace=TRUE)\nCold_Temp<-sample(1:10,20,replace=TRUE)\nGroup<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(Hot_Temp,Cold_Temp,Group)\ndf2" }, { "code": null, "e": 3209, "s": 3174, "text": "The following dataframe is created" }, { "code": null, "e": 3781, "s": 3209, "text": " Hot_Temp Cold_Temp Group\n 1 47 7 First\n 2 38 5 Third\n 3 48 7 Third\n 4 36 10 First\n 5 46 6 Third\n 6 45 2 First\n 7 35 8 Second\n 8 33 1 Second\n 9 33 4 First\n10 34 5 First\n11 34 6 Third\n12 39 10 Third\n13 47 10 First\n14 41 6 Third\n15 48 3 First\n16 36 2 Third\n17 49 9 Second\n18 35 5 Second\n19 33 1 Second\n20 49 10 Third" }, { "code": null, "e": 3910, "s": 3781, "text": "To check columns of df2 that contains string Temp on the above created data frame, add\nthe following code to the above snippet −" }, { "code": null, "e": 4134, "s": 3910, "text": "Hot_Temp<-sample(33:50,20,replace=TRUE)\nCold_Temp<-sample(1:10,20,replace=TRUE)\nGroup<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(Hot_Temp,Cold_Temp,Group)\ncolnames(df2)[grepl(\"Temp\",colnames(df2))]" }, { "code": null, "e": 4235, "s": 4134, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −" }, { "code": null, "e": 4262, "s": 4235, "text": "[1] \"Hot_Temp\" \"Cold_Temp\"" }, { "code": null, "e": 4310, "s": 4262, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 4489, "s": 4310, "text": "x1_Rate<-sample(1:10,20,replace=TRUE)\nx2_Rate<-sample(1:10,20,replace=TRUE)\nCategory<-sample(c(\"Normal\",\"Abnormal\"),20,replace=TRUE)\ndf3<-data.frame(x1_Rate,x2_Rate,Category)\ndf3" }, { "code": null, "e": 4524, "s": 4489, "text": "The following dataframe is created" }, { "code": null, "e": 5071, "s": 4524, "text": " x1_Rate x2_Rate Category\n 1 5 9 Normal\n 2 8 8 Normal\n 3 7 10 Normal\n 4 3 3 Normal\n 5 6 6 Normal\n 6 4 9 Abnormal\n 7 6 5 Abnormal\n 8 2 9 Abnormal\n 9 3 10 Abnormal\n10 7 4 Abnormal\n11 1 3 Normal\n12 9 10 Abnormal\n13 3 3 Normal\n14 8 10 Abnormal\n15 3 5 Normal\n16 2 5 Abnormal\n17 2 1 Normal\n18 5 7 Abnormal\n19 7 1 Abnormal\n20 5 8 Normal" }, { "code": null, "e": 5200, "s": 5071, "text": "To check columns of df3 that contains string Rate on the above created data frame, add\nthe following code to the above snippet −" }, { "code": null, "e": 5418, "s": 5200, "text": "x1_Rate<-sample(1:10,20,replace=TRUE)\nx2_Rate<-sample(1:10,20,replace=TRUE)\nCategory<-sample(c(\"Normal\",\"Abnormal\"),20,replace=TRUE)\ndf3<-data.frame(x1_Rate,x2_Rate,Category)\ncolnames(df3)[grepl(\"Rate\",colnames(df3))]" }, { "code": null, "e": 5519, "s": 5418, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −" }, { "code": null, "e": 5544, "s": 5519, "text": "[1] \"x1_Rate\" \"x2_Rate\"\n" } ]
Heterogeneous Arrays in Data Sturcture
As we know the arrays are homogeneous by definition. So we have to put data of same type in an array. But if we want to store data of different type, then what will be the trick? In C like old languages, we can use unions to artificially coalesce the different types into one type. Then we can define an array on this new type. Here the kind of object that an array element actually contains is determined by a tag. Let us see one structure like this − struct Vehicle{ int id; union { Bus b; Bike c; Car d; } }; Then the programmer would have to establish a convention on how the id tag will be used. Suppose, for example, when the id is 0, it means that the Vehicle which is represented is actually a Bus etc. The union allocates memory for the largest type among Bus, Bike and Car. This is wasteful for memory if there is a great disparity among the sizes of the objects. In the object oriented languages, we can use the concept of inheritances. Suppose we have a class called Vehicle, and all other types like Bus, Bike and Car are the sub-class of it. So if we define an array for Vehicle, then that can also hold all of its sub-classes. This will help us to store multiple types of data in a single array.
[ { "code": null, "e": 1515, "s": 1062, "text": "As we know the arrays are homogeneous by definition. So we have to put data of same type in an array. But if we want to store data of different type, then what will be the trick? In C like old languages, we can use unions to artificially coalesce the different types into one type. Then we can define an array on this new type. Here the kind of object that an array element actually contains is determined by a tag. Let us see one structure like this −" }, { "code": null, "e": 1601, "s": 1515, "text": "struct Vehicle{\n int id;\n union {\n Bus b;\n Bike c;\n Car d;\n }\n};" }, { "code": null, "e": 1963, "s": 1601, "text": "Then the programmer would have to establish a convention on how the id tag will be used. Suppose, for example, when the id is 0, it means that the Vehicle which is represented is actually a Bus etc. The union allocates memory for the largest type among Bus, Bike and Car. This is wasteful for memory if there is a great disparity among the sizes of the objects." }, { "code": null, "e": 2300, "s": 1963, "text": "In the object oriented languages, we can use the concept of inheritances. Suppose we have a class called Vehicle, and all other types like Bus, Bike and Car are the sub-class of it. So if we define an array for Vehicle, then that can also hold all of its sub-classes. This will help us to store multiple types of data in a single array." } ]
How to identify the difference between Kolmogorov Smirnov test and Chi Square Goodness of fit test in R?
The Chi Square Goodness of fit test is used to test whether the distribution of nominal variables is same or not as well as for other distribution matches and on the other hand the Kolmogorov Smirnov test is only used to test to the goodness of fit for a continuous data. The difference is not about the programming tool, it is a concept of statistics. Live Demo > x<-rnorm(20) > x [1] 0.078716115 -0.682154062 0.655436957 -1.169616157 -0.688543382 [6] 0.646087104 0.472429834 2.277750805 0.963105637 0.414918478 [11] 0.575005958 -1.286604138 -1.026756390 2.692769261 -0.835433410 [16] 0.007544065 0.925296720 1.058978610 0.906392907 0.973050503 > ks.test(x,pnorm) One-sample Kolmogorov-Smirnov test data: x D = 0.2609, p-value = 0.1089 alternative hypothesis: two-sided Chi-Square test: > chisq.test(x,p=rep(1/20,20)) Error in chisq.test(x, p = rep(1/20, 20)) : all entries of 'x' must be nonnegative and finite With discrete distribution − Live Demo > y<-rpois(200,5) > y [1] 6 8 7 3 5 7 6 5 2 6 4 4 3 6 6 6 6 11 7 5 4 8 6 1 3 [26] 10 4 4 9 5 2 6 4 1 5 4 4 5 1 7 8 7 3 6 6 6 2 8 7 6 [51] 7 5 5 4 6 5 3 5 3 4 4 9 3 3 3 8 3 3 2 5 4 6 6 8 4 [76] 6 12 6 1 5 5 5 0 7 4 7 7 3 2 5 5 2 5 5 4 6 4 3 4 4 [101] 4 6 5 1 2 4 4 4 8 5 8 6 3 4 5 2 3 3 3 6 7 4 4 5 3 [126] 5 5 5 8 2 5 8 1 2 3 5 9 4 3 5 6 3 6 3 6 3 7 4 4 1 [151] 3 5 0 7 2 9 6 10 2 6 4 5 1 7 2 8 7 4 2 5 4 2 4 5 6 [176] 3 9 3 9 5 9 7 3 1 3 9 5 6 3 10 7 5 5 6 7 4 2 5 5 1 > chisq.test(y,p=rep(1/200,200)) Chi-squared test for given probabilities data: y X-squared = 203.61, df = 199, p-value = 0.3964 Warning message: In chisq.test(y, p = rep(1/200, 200)) : Chi-squared approximation may be incorrect Live Demo > a<-sample(0:9,100,replace=TRUE) > a [1] 4 6 1 8 1 7 3 9 8 5 4 0 7 2 2 4 6 2 1 2 1 9 1 3 1 9 2 9 1 8 4 0 4 7 1 7 1 [38] 0 1 5 9 6 5 4 6 6 9 6 1 0 8 9 4 8 2 8 1 6 9 1 0 4 6 8 8 1 1 0 3 2 6 7 2 1 [75] 7 9 9 8 2 6 4 7 3 4 0 9 5 5 9 4 5 7 8 7 3 0 1 4 8 5 > ks.test(a,pnorm) One-sample Kolmogorov-Smirnov test data: a D = 0.76134, p-value < 2.2e-16 alternative hypothesis: two-sided Warning message: In ks.test(a, pnorm) : ties should not be present for the Kolmogorov-Smirnov test > chisq.test(a,p=rep(1/100,100)) Chi-squared test for given probabilities data: a X-squared = 198.88, df = 99, p-value = 1.096e-08 Warning message: In chisq.test(a, p = rep(1/100, 100)) : Chi-squared approximation may be incorrect
[ { "code": null, "e": 1415, "s": 1062, "text": "The Chi Square Goodness of fit test is used to test whether the distribution of nominal variables is same or not as well as for other distribution matches and on the other hand the Kolmogorov Smirnov test is only used to test to the goodness of fit for a continuous data. The difference is not about the programming tool, it is a concept of statistics." }, { "code": null, "e": 1425, "s": 1415, "text": "Live Demo" }, { "code": null, "e": 1444, "s": 1425, "text": "> x<-rnorm(20)\n> x" }, { "code": null, "e": 1708, "s": 1444, "text": "[1] 0.078716115 -0.682154062 0.655436957 -1.169616157 -0.688543382\n[6] 0.646087104 0.472429834 2.277750805 0.963105637 0.414918478\n[11] 0.575005958 -1.286604138 -1.026756390 2.692769261 -0.835433410\n[16] 0.007544065 0.925296720 1.058978610 0.906392907 0.973050503" }, { "code": null, "e": 1979, "s": 1708, "text": "> ks.test(x,pnorm)\n\nOne-sample Kolmogorov-Smirnov test\n\ndata: x\nD = 0.2609, p-value = 0.1089\nalternative hypothesis: two-sided\n\nChi-Square test:\n\n> chisq.test(x,p=rep(1/20,20))\nError in chisq.test(x, p = rep(1/20, 20)) :\nall entries of 'x' must be nonnegative and finite" }, { "code": null, "e": 2008, "s": 1979, "text": "With discrete distribution −" }, { "code": null, "e": 2018, "s": 2008, "text": "Live Demo" }, { "code": null, "e": 2040, "s": 2018, "text": "> y<-rpois(200,5)\n> y" }, { "code": null, "e": 2488, "s": 2040, "text": "[1] 6 8 7 3 5 7 6 5 2 6 4 4 3 6 6 6 6 11 7 5 4 8 6 1 3\n[26] 10 4 4 9 5 2 6 4 1 5 4 4 5 1 7 8 7 3 6 6 6 2 8 7 6\n[51] 7 5 5 4 6 5 3 5 3 4 4 9 3 3 3 8 3 3 2 5 4 6 6 8 4\n[76] 6 12 6 1 5 5 5 0 7 4 7 7 3 2 5 5 2 5 5 4 6 4 3 4 4\n[101] 4 6 5 1 2 4 4 4 8 5 8 6 3 4 5 2 3 3 3 6 7 4 4 5 3\n[126] 5 5 5 8 2 5 8 1 2 3 5 9 4 3 5 6 3 6 3 6 3 7 4 4 1\n[151] 3 5 0 7 2 9 6 10 2 6 4 5 1 7 2 8 7 4 2 5 4 2 4 5 6\n[176] 3 9 3 9 5 9 7 3 1 3 9 5 6 3 10 7 5 5 6 7 4 2 5 5 1" }, { "code": null, "e": 2720, "s": 2488, "text": "> chisq.test(y,p=rep(1/200,200))\n\nChi-squared test for given probabilities\n\ndata: y\nX-squared = 203.61, df = 199, p-value = 0.3964\n\nWarning message:\nIn chisq.test(y, p = rep(1/200, 200)) :\nChi-squared approximation may be incorrect" }, { "code": null, "e": 2730, "s": 2720, "text": "Live Demo" }, { "code": null, "e": 2768, "s": 2730, "text": "> a<-sample(0:9,100,replace=TRUE)\n> a" }, { "code": null, "e": 2982, "s": 2768, "text": "[1] 4 6 1 8 1 7 3 9 8 5 4 0 7 2 2 4 6 2 1 2 1 9 1 3 1 9 2 9 1 8 4 0 4 7 1 7 1\n[38] 0 1 5 9 6 5 4 6 6 9 6 1 0 8 9 4 8 2 8 1 6 9 1 0 4 6 8 8 1 1 0 3 2 6 7 2 1\n[75] 7 9 9 8 2 6 4 7 3 4 0 9 5 5 9 4 5 7 8 7 3 0 1 4 8 5" }, { "code": null, "e": 3445, "s": 2982, "text": "> ks.test(a,pnorm)\n\nOne-sample Kolmogorov-Smirnov test\n\ndata: a\nD = 0.76134, p-value < 2.2e-16\nalternative hypothesis: two-sided\n\nWarning message:\nIn ks.test(a, pnorm) :\nties should not be present for the Kolmogorov-Smirnov test\n> chisq.test(a,p=rep(1/100,100))\n\nChi-squared test for given probabilities\n\ndata: a\nX-squared = 198.88, df = 99, p-value = 1.096e-08\n\nWarning message:\nIn chisq.test(a, p = rep(1/100, 100)) :\nChi-squared approximation may be incorrect" } ]
How to use CSS style in PowerShell HTML Output?
Cascading Style Sheets (CSS) in general used for formatting HTML with styles. It describes how the HTML elements should be displayed. Once we get the output from the Convertto-HTML command, we can use the CSS style to make the output more stylish. Consider we have the below example for converting the services output table to the HTML. Get-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title "Services" -PreContent "<h1>Services Output</h1>" | Out-File Servicesoutput.html The output is simple for the above command in HTML. There are multiple ways to add the CSS style in the above HTML file so the file output becomes more stylish. We will use the most common ways to add the CSS style. Header Header CSSURI CSSURI Header Method. Header Method. Convertto-HTML cmdlet supports the -Head property. We can provide header for the HTML along with <style></style> tag so that the PowerShell can understand the style. For example, Convertto-HTML cmdlet supports the -Head property. We can provide header for the HTML along with <style></style> tag so that the PowerShell can understand the style. For example, $head = @" <style> body { background-color: Gainsboro; } table, th, td{ border: 1px solid; } h1{ background-color:Tomato; color:white; text-align: center; } </style> "@ Get-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title "Services" -PreContent "<h1>Services Output</h1>" -Head $head | Out-File Servicesoutput.html In the above script, we have used $head as an array so we can cover the entire CSS script in between <style></style> tags. The first element is the HTML body and we are providing Gainsboro for the background color of the web page. Next, we are table, th (table header) and td (table data) to cover its borders and at the last, we used -Precontent property between <h1></h1> tag and at the same time we have mentioned h1 tag inside the CSS file so we provide different attributes as per our style requirement. Similarly, you can use the CSS reference guide and play with multiple styles. This method is simple because you don't need to provide the separate CSS file to other users when you share the script but the problem is that the script becomes sometimes lengthy when you add more styles. To overcome this problem, we can provide the external CSS file to the Convertto-HTML cmdlet as shown in the second method. Cssuri method (External CSV) Cssuri method (External CSV) In this method, instead of providing Header property to Convertto-HTML cmdlet, we can use cssuri property to link the external CSS file. CSS file will remain same as mentioned in the first method, except <style></style> parameter won't be added. First, we will check the CSS file saved with the name Style.css and then we will see the script to link the external CSS file. In this method, instead of providing Header property to Convertto-HTML cmdlet, we can use cssuri property to link the external CSS file. CSS file will remain same as mentioned in the first method, except <style></style> parameter won't be added. First, we will check the CSS file saved with the name Style.css and then we will see the script to link the external CSS file. body { background-color: Gainsboro; } table, th, td{ border: 1px ridge; } h1{ background-color:Tomato; color:white; text-align: center; } Get-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title "Services" -PreContent "Services Output" -CssUri .\style.css | Out-File Servicesoutput.html As mentioned earlier in separate CSS file, you don't need to mention the <style></style> tag. In the above command, we have provided the path of the CSS file to -Cssuri cmdlet. Here, script and the CSS file both are at the same location. If the CSS file resides on a different location, you need to provide the full path of the CSS file. The output remains the same as shown in the first example.
[ { "code": null, "e": 1196, "s": 1062, "text": "Cascading Style Sheets (CSS) in general used for formatting HTML with styles. It describes how the HTML elements should be displayed." }, { "code": null, "e": 1310, "s": 1196, "text": "Once we get the output from the Convertto-HTML command, we can use the CSS style to make the output more stylish." }, { "code": null, "e": 1399, "s": 1310, "text": "Consider we have the below example for converting the services output table to the HTML." }, { "code": null, "e": 1562, "s": 1399, "text": "Get-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title \"Services\" -PreContent \"<h1>Services Output</h1>\" | Out-File Servicesoutput.html" }, { "code": null, "e": 1614, "s": 1562, "text": "The output is simple for the above command in HTML." }, { "code": null, "e": 1778, "s": 1614, "text": "There are multiple ways to add the CSS style in the above HTML file so the file output becomes more stylish. We will use the most common ways to add the CSS style." }, { "code": null, "e": 1785, "s": 1778, "text": "Header" }, { "code": null, "e": 1792, "s": 1785, "text": "Header" }, { "code": null, "e": 1799, "s": 1792, "text": "CSSURI" }, { "code": null, "e": 1806, "s": 1799, "text": "CSSURI" }, { "code": null, "e": 1821, "s": 1806, "text": "Header Method." }, { "code": null, "e": 1836, "s": 1821, "text": "Header Method." }, { "code": null, "e": 2015, "s": 1836, "text": "Convertto-HTML cmdlet supports the -Head property. We can provide header for the HTML along with <style></style> tag so that the PowerShell can understand the style. For example," }, { "code": null, "e": 2194, "s": 2015, "text": "Convertto-HTML cmdlet supports the -Head property. We can provide header for the HTML along with <style></style> tag so that the PowerShell can understand the style. For example," }, { "code": null, "e": 2602, "s": 2194, "text": "$head = @\"\n\n<style>\n body\n {\n background-color: Gainsboro;\n }\n\n table, th, td{\n border: 1px solid;\n }\n\n h1{\n background-color:Tomato;\n color:white;\n text-align: center;\n }\n</style>\n\"@\n\nGet-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title \"Services\" -PreContent \"<h1>Services Output</h1>\" -Head $head | Out-File Servicesoutput.html" }, { "code": null, "e": 2725, "s": 2602, "text": "In the above script, we have used $head as an array so we can cover the entire CSS script in between <style></style> tags." }, { "code": null, "e": 3111, "s": 2725, "text": "The first element is the HTML body and we are providing Gainsboro for the background color of the web page. Next, we are table, th (table header) and td (table data) to cover its borders and at the last, we used -Precontent property between <h1></h1> tag and at the same time we have mentioned h1 tag inside the CSS file so we provide different attributes as per our style requirement." }, { "code": null, "e": 3518, "s": 3111, "text": "Similarly, you can use the CSS reference guide and play with multiple styles. This method is simple because you don't need to provide the separate CSS file to other users when you share the script but the problem is that the script becomes sometimes lengthy when you add more styles. To overcome this problem, we can provide the external CSS file to the Convertto-HTML cmdlet as shown in the second method." }, { "code": null, "e": 3547, "s": 3518, "text": "Cssuri method (External CSV)" }, { "code": null, "e": 3576, "s": 3547, "text": "Cssuri method (External CSV)" }, { "code": null, "e": 3949, "s": 3576, "text": "In this method, instead of providing Header property to Convertto-HTML cmdlet, we can use cssuri property to link the external CSS file. CSS file will remain same as mentioned in the first method, except <style></style> parameter won't be added. First, we will check the CSS file saved with the name Style.css and then we will see the script to link the external CSS file." }, { "code": null, "e": 4322, "s": 3949, "text": "In this method, instead of providing Header property to Convertto-HTML cmdlet, we can use cssuri property to link the external CSS file. CSS file will remain same as mentioned in the first method, except <style></style> parameter won't be added. First, we will check the CSS file saved with the name Style.css and then we will see the script to link the external CSS file." }, { "code": null, "e": 4487, "s": 4322, "text": "body\n {\n background-color: Gainsboro;\n }\n\ntable, th, td{\n border: 1px ridge;\n}\n\nh1{\n background-color:Tomato;\n color:white;\n text-align: center;\n}\n" }, { "code": null, "e": 4661, "s": 4487, "text": "Get-Service | Select Name, DisplayName, Status, StartType | ConvertTo-Html -Title \"Services\" -PreContent \"Services Output\" -CssUri .\\style.css | Out-File Servicesoutput.html" }, { "code": null, "e": 5058, "s": 4661, "text": "As mentioned earlier in separate CSS file, you don't need to mention the <style></style> tag. In the above command, we have provided the path of the CSS file to -Cssuri cmdlet. Here, script and the CSS file both are at the same location. If the CSS file resides on a different location, you need to provide the full path of the CSS file. The output remains the same as shown in the first example." } ]
How do I put a border around an Android textview?
If you wants to see text view as 3D view as we seen in Microsoft power point 3d texts. This example demonstrate about how do I put a border around an Android text view. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="#dde4dd" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="18sp" android:layout_width="wrap_content" android:background="@drawable/ border " android:layout_height="wrap_content" /> </LinearLayout> In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.xml and add the following content. <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="@android:color/white" /> <stroke android:width="1dip" android:color="#4fa5d5"/> <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/> </shape> In the above code we have taken shape as root tag and given shape is rectangle and added width and padding for shape. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.w3c.dom.Text; import java.util.Locale; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView=findViewById(R.id.text); textView.setText("Tutorialspoint india pvt ltd"); } } 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 Runicon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, we have added boarder to text view. Click here to download the project code
[ { "code": null, "e": 1231, "s": 1062, "text": "If you wants to see text view as 3D view as we seen in Microsoft power point 3d texts. This example demonstrate\nabout how do I put a border around an Android text view." }, { "code": null, "e": 1360, "s": 1231, "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": 1425, "s": 1360, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2016, "s": 1425, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:background=\"#dde4dd\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:layout_width=\"wrap_content\"\n android:background=\"@drawable/ border \"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2174, "s": 2016, "text": "In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.xml and add the following content." }, { "code": null, "e": 2520, "s": 2174, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\" >\n <solid android:color=\"@android:color/white\" />\n <stroke android:width=\"1dip\" android:color=\"#4fa5d5\"/>\n <padding android:bottom=\"10dp\" android:left=\"10dp\" android:right=\"10dp\" android:top=\"10dp\"/>\n</shape>" }, { "code": null, "e": 2638, "s": 2520, "text": "In the above code we have taken shape as root tag and given shape is rectangle and added width and padding for shape." }, { "code": null, "e": 2695, "s": 2638, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3272, "s": 2695, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport org.w3c.dom.Text;\nimport java.util.Locale;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView=findViewById(R.id.text);\n textView.setText(\"Tutorialspoint india pvt ltd\");\n }\n}" }, { "code": null, "e": 3617, "s": 3272, "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 Runicon 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": 3674, "s": 3617, "text": "In the above result, we have added boarder to text view." }, { "code": null, "e": 3714, "s": 3674, "text": "Click here to download the project code" } ]
PyTorch [Tabular] — Binary Classification | by Akshaj Verma | Towards Data Science
We will use the lower back pain symptoms dataset available on Kaggle. This dataset has 13 columns where the first 12 are the features and the last column is the target column. The data set has 300 rows. import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoaderfrom sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, classification_report df = pd.read_csv("data/tabular/classification/spine_dataset.csv")df.head() There is a class imbalance here. While there’s a lot that can be done to combat class imbalance, it outside the scope of this blog post. sns.countplot(x = 'Class_att', data=df) PyTorch supports labels starting from 0. That is [0, n]. We need to remap our labels to start from 0. df['Class_att'] = df['Class_att'].astype('category')encode_map = { 'Abnormal': 1, 'Normal': 0}df['Class_att'].replace(encode_map, inplace=True) The last column is our output. The input is all the columns but the last one. Here we use .iloc method from the Pandas library to select our input and output columns. X = df.iloc[:, 0:-1]y = df.iloc[:, -1] We now split our data into train and test sets. We’ve selected 33% percent of out data to be in the test set. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=69) For neural networks to train properly, we need to standardize the input values. We standardize features by removing the mean and scaling to unit variance. The standard score of a sample x where the mean is u and the standard deviation is s is calculated as: z = (x — u) / s You can find more about standardization/normalization in neural nets here. scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test) To train our models, we need to set some hyper-parameters. Note that this is a very simple neural network, as a result, we do not tune a lot of hyper-parameters. The goal is to get to know how PyTorch works. EPOCHS = 50BATCH_SIZE = 64LEARNING_RATE = 0.001 Here we define a Dataloader. If this is new to you, I suggest you read the following blog post on Dataloaders and come back. towardsdatascience.com ## train dataclass TrainData(Dataset): def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data)train_data = TrainData(torch.FloatTensor(X_train), torch.FloatTensor(y_train))## test data class TestData(Dataset): def __init__(self, X_data): self.X_data = X_data def __getitem__(self, index): return self.X_data[index] def __len__ (self): return len(self.X_data) test_data = TestData(torch.FloatTensor(X_test)) Let’s initialize our dataloaders. We’ll use a batch_size = 1 for our test dataloader. train_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)test_loader = DataLoader(dataset=test_data, batch_size=1) Here, we define a 2 layer Feed-Forward network with BatchNorm and Dropout. In our __init__() function, we define the what layers we want to use while in the forward() function we call the defined layers. Since the number of input features in our dataset is 12, the input to our first nn.Linear layer would be 12. The output could be any number you want. The only thing you need to ensure is that number of output features of one layer should be equal to the input features of the next layer. Read more about nn.Linear in the docs. Similarly, we define ReLU, Dropout, and BatchNorm layers. Once we’ve defined all these layers, it’s time to use them. In the forward() function, we take variable inputs as our input. We pass this input through the different layers we initialized. The first line of the forward() functions takes the input, passes it through our first linear layer and then applies the ReLU activation on it. Then we apply BatchNorm on the output. Look at the following code to understand it better. Note that we did not use the Sigmoid activation in our final layer during training. That’s because, we use the nn.BCEWithLogitsLoss() loss function which automatically applies the the Sigmoid activation. class BinaryClassification(nn.Module): def __init__(self): super(BinaryClassification, self).__init__() # Number of input features is 12. self.layer_1 = nn.Linear(12, 64) self.layer_2 = nn.Linear(64, 64) self.layer_out = nn.Linear(64, 1) self.relu = nn.ReLU() self.dropout = nn.Dropout(p=0.1) self.batchnorm1 = nn.BatchNorm1d(64) self.batchnorm2 = nn.BatchNorm1d(64) def forward(self, inputs): x = self.relu(self.layer_1(inputs)) x = self.batchnorm1(x) x = self.relu(self.layer_2(x)) x = self.batchnorm2(x) x = self.dropout(x) x = self.layer_out(x) return x Once, we’ve defined our architecture, we check if our GPU is active. The amazing thing about PyTorch is that it’s super easy to use the GPU. The variable device will either say cuda:0 if we have the GPU. If not, it’ll say cpu . You can follow along this tutorial even if you do not have a GPU without any change in code. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")print(device)###################### OUTPUT ######################cuda:0 Next, we need to initialize our model. After initializing it, we move it to device . Now, this device is a GPU if you have one or it’s CPU if you don’t. The network we’ve used is fairly small. So, it will not take a lot of time to train on a CPU. After this, we initialize our optimizer and decide on which loss function to use. model = BinaryClassification()model.to(device)print(model)criterion = nn.BCEWithLogitsLoss()optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)###################### OUTPUT ######################BinaryClassification( (layer_1): Linear(in_features=12, out_features=64, bias=True) (layer_2): Linear(in_features=64, out_features=64, bias=True) (layer_out): Linear(in_features=64, out_features=1, bias=True) (relu): ReLU() (dropout): Dropout(p=0.1, inplace=False) (batchnorm1): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (batchnorm2): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)) Before we start the actual training, let’s define a function to calculate accuracy. In the function below, we take the predicted and actual output as the input. The predicted value(a probability) is rounded off to convert it into either a 0 or a 1. Once that is done, we simply compare the number of 1/0 we predicted to the number of 1/0 actually present and calculate the accuracy. Note that the inputs y_pred and y_test are for a batch. Our batch_size was 64. So, this accuracy is being calculated for 64 predictions(tensors) at a time. def binary_acc(y_pred, y_test): y_pred_tag = torch.round(torch.sigmoid(y_pred)) correct_results_sum = (y_pred_tag == y_test).sum().float() acc = correct_results_sum/y_test.shape[0] acc = torch.round(acc * 100) return acc The moment we’ve been waiting for has arrived. Let’s train our model. You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you’re in training mode. Well, why do we need to do that? If you’re using layers such as Dropout or BatchNorm which behave differently during training and evaluation, you need to tell PyTorch to act accordingly. While the default mode in PyTorch is the train, so, you don’t explicitly have to write that. But it’s good practice. Similarly, we’ll call model.eval() when we test our model. We’ll see that below. Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss and accuracy per epoch to 0. After every epoch, we’ll print out the loss/accuracy and reset it back to 0. Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader. We do optimizer.zero_grad() before we make any predictions. Since the backward() function accumulates gradients, we need to set it to 0 manually per mini-batch. From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform backpropagation using loss.backward() and optimizer.step() . Finally, we add all the mini-batch losses (and accuracies) to obtain the average loss (and accuracy) for that epoch. This loss and accuracy is printed out in the outer for loop. model.train()for e in range(1, EPOCHS+1): epoch_loss = 0 epoch_acc = 0 for X_batch, y_batch in train_loader: X_batch, y_batch = X_batch.to(device), y_batch.to(device) optimizer.zero_grad() y_pred = model(X_batch) loss = criterion(y_pred, y_batch.unsqueeze(1)) acc = binary_acc(y_pred, y_batch.unsqueeze(1)) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() print(f'Epoch {e+0:03}: | Loss: {epoch_loss/len(train_loader):.5f} | Acc: {epoch_acc/len(train_loader):.3f}')###################### OUTPUT ######################Epoch 001: | Loss: 0.04027 | Acc: 98.250Epoch 002: | Loss: 0.12023 | Acc: 96.750Epoch 003: | Loss: 0.02067 | Acc: 99.500Epoch 004: | Loss: 0.07329 | Acc: 96.250Epoch 005: | Loss: 0.04676 | Acc: 99.250Epoch 006: | Loss: 0.03005 | Acc: 99.500Epoch 007: | Loss: 0.05777 | Acc: 98.250Epoch 008: | Loss: 0.03446 | Acc: 99.500Epoch 009: | Loss: 0.03443 | Acc: 100.000Epoch 010: | Loss: 0.03368 | Acc: 100.000Epoch 011: | Loss: 0.02395 | Acc: 100.000Epoch 012: | Loss: 0.05094 | Acc: 98.250Epoch 013: | Loss: 0.03618 | Acc: 98.250Epoch 014: | Loss: 0.02143 | Acc: 100.000Epoch 015: | Loss: 0.02730 | Acc: 99.500Epoch 016: | Loss: 0.02323 | Acc: 100.000Epoch 017: | Loss: 0.03395 | Acc: 98.250Epoch 018: | Loss: 0.08600 | Acc: 96.750Epoch 019: | Loss: 0.02394 | Acc: 100.000Epoch 020: | Loss: 0.02363 | Acc: 100.000Epoch 021: | Loss: 0.01660 | Acc: 100.000Epoch 022: | Loss: 0.05766 | Acc: 96.750Epoch 023: | Loss: 0.02115 | Acc: 100.000Epoch 024: | Loss: 0.01331 | Acc: 100.000Epoch 025: | Loss: 0.01504 | Acc: 100.000Epoch 026: | Loss: 0.01727 | Acc: 100.000Epoch 027: | Loss: 0.02128 | Acc: 100.000Epoch 028: | Loss: 0.01106 | Acc: 100.000Epoch 029: | Loss: 0.05802 | Acc: 98.250Epoch 030: | Loss: 0.01275 | Acc: 100.000Epoch 031: | Loss: 0.01272 | Acc: 100.000Epoch 032: | Loss: 0.01949 | Acc: 100.000Epoch 033: | Loss: 0.02848 | Acc: 100.000Epoch 034: | Loss: 0.01514 | Acc: 100.000Epoch 035: | Loss: 0.02949 | Acc: 100.000Epoch 036: | Loss: 0.00895 | Acc: 100.000Epoch 037: | Loss: 0.01692 | Acc: 100.000Epoch 038: | Loss: 0.01678 | Acc: 100.000Epoch 039: | Loss: 0.02755 | Acc: 100.000Epoch 040: | Loss: 0.02021 | Acc: 100.000Epoch 041: | Loss: 0.07972 | Acc: 98.250Epoch 042: | Loss: 0.01421 | Acc: 100.000Epoch 043: | Loss: 0.01558 | Acc: 100.000Epoch 044: | Loss: 0.01185 | Acc: 100.000Epoch 045: | Loss: 0.01830 | Acc: 100.000Epoch 046: | Loss: 0.01367 | Acc: 100.000Epoch 047: | Loss: 0.00880 | Acc: 100.000Epoch 048: | Loss: 0.01046 | Acc: 100.000Epoch 049: | Loss: 0.00933 | Acc: 100.000Epoch 050: | Loss: 0.11034 | Acc: 98.250 After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad() which reduces memory usage and speeds up computation. We start by defining a list that will hold our predictions. Then we loop through our batches using the test_loader. For each batch — We make the predictions using our trained model. Round off the probabilities to 1 or 0. Move the batch to the GPU from the CPU. Convert the tensor to a numpy object and append it to our list. Flatten out the list so that we can use it as an input to confusion_matrix and classification_report . y_pred_list = []model.eval()with torch.no_grad(): for X_batch in test_loader: X_batch = X_batch.to(device) y_test_pred = model(X_batch) y_test_pred = torch.sigmoid(y_test_pred) y_pred_tag = torch.round(y_test_pred) y_pred_list.append(y_pred_tag.cpu().numpy())y_pred_list = [a.squeeze().tolist() for a in y_pred_list] Once we have all our predictions, we use the confusion_matrix() function from scikit-learn to calculate the confusion matrix. confusion_matrix(y_test, y_pred_list)###################### OUTPUT ######################array([[23, 8], [12, 60]]) To obtain the classification report which has precision, recall, and F1 score, we use the function classification_report . print(classification_report(y_test, y_pred_list))###################### OUTPUT ######################precision recall f1-score support 0 0.66 0.74 0.70 31 1 0.88 0.83 0.86 72 accuracy 0.81 103 macro avg 0.77 0.79 0.78 103weighted avg 0.81 0.81 0.81 103 Thank you for reading. Suggestions and constructive criticism are welcome. :) This blogpost is a part of the series —” How to train you Neural Net”. You can find the series here. You can find me on LinkedIn and Twitter. If you liked this, check out my other blogposts.
[ { "code": null, "e": 250, "s": 47, "text": "We will use the lower back pain symptoms dataset available on Kaggle. This dataset has 13 columns where the first 12 are the features and the last column is the target column. The data set has 300 rows." }, { "code": null, "e": 619, "s": 250, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoaderfrom sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrix, classification_report" }, { "code": null, "e": 694, "s": 619, "text": "df = pd.read_csv(\"data/tabular/classification/spine_dataset.csv\")df.head()" }, { "code": null, "e": 831, "s": 694, "text": "There is a class imbalance here. While there’s a lot that can be done to combat class imbalance, it outside the scope of this blog post." }, { "code": null, "e": 871, "s": 831, "text": "sns.countplot(x = 'Class_att', data=df)" }, { "code": null, "e": 973, "s": 871, "text": "PyTorch supports labels starting from 0. That is [0, n]. We need to remap our labels to start from 0." }, { "code": null, "e": 1123, "s": 973, "text": "df['Class_att'] = df['Class_att'].astype('category')encode_map = { 'Abnormal': 1, 'Normal': 0}df['Class_att'].replace(encode_map, inplace=True)" }, { "code": null, "e": 1290, "s": 1123, "text": "The last column is our output. The input is all the columns but the last one. Here we use .iloc method from the Pandas library to select our input and output columns." }, { "code": null, "e": 1329, "s": 1290, "text": "X = df.iloc[:, 0:-1]y = df.iloc[:, -1]" }, { "code": null, "e": 1439, "s": 1329, "text": "We now split our data into train and test sets. We’ve selected 33% percent of out data to be in the test set." }, { "code": null, "e": 1530, "s": 1439, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=69)" }, { "code": null, "e": 1788, "s": 1530, "text": "For neural networks to train properly, we need to standardize the input values. We standardize features by removing the mean and scaling to unit variance. The standard score of a sample x where the mean is u and the standard deviation is s is calculated as:" }, { "code": null, "e": 1804, "s": 1788, "text": "z = (x — u) / s" }, { "code": null, "e": 1879, "s": 1804, "text": "You can find more about standardization/normalization in neural nets here." }, { "code": null, "e": 1977, "s": 1879, "text": "scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)" }, { "code": null, "e": 2185, "s": 1977, "text": "To train our models, we need to set some hyper-parameters. Note that this is a very simple neural network, as a result, we do not tune a lot of hyper-parameters. The goal is to get to know how PyTorch works." }, { "code": null, "e": 2233, "s": 2185, "text": "EPOCHS = 50BATCH_SIZE = 64LEARNING_RATE = 0.001" }, { "code": null, "e": 2358, "s": 2233, "text": "Here we define a Dataloader. If this is new to you, I suggest you read the following blog post on Dataloaders and come back." }, { "code": null, "e": 2381, "s": 2358, "text": "towardsdatascience.com" }, { "code": null, "e": 3066, "s": 2381, "text": "## train dataclass TrainData(Dataset): def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data)train_data = TrainData(torch.FloatTensor(X_train), torch.FloatTensor(y_train))## test data class TestData(Dataset): def __init__(self, X_data): self.X_data = X_data def __getitem__(self, index): return self.X_data[index] def __len__ (self): return len(self.X_data) test_data = TestData(torch.FloatTensor(X_test))" }, { "code": null, "e": 3152, "s": 3066, "text": "Let’s initialize our dataloaders. We’ll use a batch_size = 1 for our test dataloader." }, { "code": null, "e": 3292, "s": 3152, "text": "train_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)test_loader = DataLoader(dataset=test_data, batch_size=1)" }, { "code": null, "e": 3367, "s": 3292, "text": "Here, we define a 2 layer Feed-Forward network with BatchNorm and Dropout." }, { "code": null, "e": 3496, "s": 3367, "text": "In our __init__() function, we define the what layers we want to use while in the forward() function we call the defined layers." }, { "code": null, "e": 3646, "s": 3496, "text": "Since the number of input features in our dataset is 12, the input to our first nn.Linear layer would be 12. The output could be any number you want." }, { "code": null, "e": 3784, "s": 3646, "text": "The only thing you need to ensure is that number of output features of one layer should be equal to the input features of the next layer." }, { "code": null, "e": 3881, "s": 3784, "text": "Read more about nn.Linear in the docs. Similarly, we define ReLU, Dropout, and BatchNorm layers." }, { "code": null, "e": 4070, "s": 3881, "text": "Once we’ve defined all these layers, it’s time to use them. In the forward() function, we take variable inputs as our input. We pass this input through the different layers we initialized." }, { "code": null, "e": 4305, "s": 4070, "text": "The first line of the forward() functions takes the input, passes it through our first linear layer and then applies the ReLU activation on it. Then we apply BatchNorm on the output. Look at the following code to understand it better." }, { "code": null, "e": 4509, "s": 4305, "text": "Note that we did not use the Sigmoid activation in our final layer during training. That’s because, we use the nn.BCEWithLogitsLoss() loss function which automatically applies the the Sigmoid activation." }, { "code": null, "e": 5211, "s": 4509, "text": "class BinaryClassification(nn.Module): def __init__(self): super(BinaryClassification, self).__init__() # Number of input features is 12. self.layer_1 = nn.Linear(12, 64) self.layer_2 = nn.Linear(64, 64) self.layer_out = nn.Linear(64, 1) self.relu = nn.ReLU() self.dropout = nn.Dropout(p=0.1) self.batchnorm1 = nn.BatchNorm1d(64) self.batchnorm2 = nn.BatchNorm1d(64) def forward(self, inputs): x = self.relu(self.layer_1(inputs)) x = self.batchnorm1(x) x = self.relu(self.layer_2(x)) x = self.batchnorm2(x) x = self.dropout(x) x = self.layer_out(x) return x" }, { "code": null, "e": 5352, "s": 5211, "text": "Once, we’ve defined our architecture, we check if our GPU is active. The amazing thing about PyTorch is that it’s super easy to use the GPU." }, { "code": null, "e": 5532, "s": 5352, "text": "The variable device will either say cuda:0 if we have the GPU. If not, it’ll say cpu . You can follow along this tutorial even if you do not have a GPU without any change in code." }, { "code": null, "e": 5675, "s": 5532, "text": "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")print(device)###################### OUTPUT ######################cuda:0" }, { "code": null, "e": 5922, "s": 5675, "text": "Next, we need to initialize our model. After initializing it, we move it to device . Now, this device is a GPU if you have one or it’s CPU if you don’t. The network we’ve used is fairly small. So, it will not take a lot of time to train on a CPU." }, { "code": null, "e": 6004, "s": 5922, "text": "After this, we initialize our optimizer and decide on which loss function to use." }, { "code": null, "e": 6669, "s": 6004, "text": "model = BinaryClassification()model.to(device)print(model)criterion = nn.BCEWithLogitsLoss()optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)###################### OUTPUT ######################BinaryClassification( (layer_1): Linear(in_features=12, out_features=64, bias=True) (layer_2): Linear(in_features=64, out_features=64, bias=True) (layer_out): Linear(in_features=64, out_features=1, bias=True) (relu): ReLU() (dropout): Dropout(p=0.1, inplace=False) (batchnorm1): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (batchnorm2): BatchNorm1d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True))" }, { "code": null, "e": 6753, "s": 6669, "text": "Before we start the actual training, let’s define a function to calculate accuracy." }, { "code": null, "e": 6918, "s": 6753, "text": "In the function below, we take the predicted and actual output as the input. The predicted value(a probability) is rounded off to convert it into either a 0 or a 1." }, { "code": null, "e": 7052, "s": 6918, "text": "Once that is done, we simply compare the number of 1/0 we predicted to the number of 1/0 actually present and calculate the accuracy." }, { "code": null, "e": 7208, "s": 7052, "text": "Note that the inputs y_pred and y_test are for a batch. Our batch_size was 64. So, this accuracy is being calculated for 64 predictions(tensors) at a time." }, { "code": null, "e": 7448, "s": 7208, "text": "def binary_acc(y_pred, y_test): y_pred_tag = torch.round(torch.sigmoid(y_pred)) correct_results_sum = (y_pred_tag == y_test).sum().float() acc = correct_results_sum/y_test.shape[0] acc = torch.round(acc * 100) return acc" }, { "code": null, "e": 7518, "s": 7448, "text": "The moment we’ve been waiting for has arrived. Let’s train our model." }, { "code": null, "e": 7638, "s": 7518, "text": "You can see we’ve put a model.train() at the before the loop. model.train() tells PyTorch that you’re in training mode." }, { "code": null, "e": 7942, "s": 7638, "text": "Well, why do we need to do that? If you’re using layers such as Dropout or BatchNorm which behave differently during training and evaluation, you need to tell PyTorch to act accordingly. While the default mode in PyTorch is the train, so, you don’t explicitly have to write that. But it’s good practice." }, { "code": null, "e": 8023, "s": 7942, "text": "Similarly, we’ll call model.eval() when we test our model. We’ll see that below." }, { "code": null, "e": 8220, "s": 8023, "text": "Back to training; we start a for-loop. At the top of this for-loop, we initialize our loss and accuracy per epoch to 0. After every epoch, we’ll print out the loss/accuracy and reset it back to 0." }, { "code": null, "e": 8323, "s": 8220, "text": "Then we have another for-loop. This for-loop is used to get our data in batches from the train_loader." }, { "code": null, "e": 8484, "s": 8323, "text": "We do optimizer.zero_grad() before we make any predictions. Since the backward() function accumulates gradients, we need to set it to 0 manually per mini-batch." }, { "code": null, "e": 8771, "s": 8484, "text": "From our defined model, we then obtain a prediction, get the loss(and accuracy) for that mini-batch, perform backpropagation using loss.backward() and optimizer.step() . Finally, we add all the mini-batch losses (and accuracies) to obtain the average loss (and accuracy) for that epoch." }, { "code": null, "e": 8832, "s": 8771, "text": "This loss and accuracy is printed out in the outer for loop." }, { "code": null, "e": 11532, "s": 8832, "text": "model.train()for e in range(1, EPOCHS+1): epoch_loss = 0 epoch_acc = 0 for X_batch, y_batch in train_loader: X_batch, y_batch = X_batch.to(device), y_batch.to(device) optimizer.zero_grad() y_pred = model(X_batch) loss = criterion(y_pred, y_batch.unsqueeze(1)) acc = binary_acc(y_pred, y_batch.unsqueeze(1)) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() print(f'Epoch {e+0:03}: | Loss: {epoch_loss/len(train_loader):.5f} | Acc: {epoch_acc/len(train_loader):.3f}')###################### OUTPUT ######################Epoch 001: | Loss: 0.04027 | Acc: 98.250Epoch 002: | Loss: 0.12023 | Acc: 96.750Epoch 003: | Loss: 0.02067 | Acc: 99.500Epoch 004: | Loss: 0.07329 | Acc: 96.250Epoch 005: | Loss: 0.04676 | Acc: 99.250Epoch 006: | Loss: 0.03005 | Acc: 99.500Epoch 007: | Loss: 0.05777 | Acc: 98.250Epoch 008: | Loss: 0.03446 | Acc: 99.500Epoch 009: | Loss: 0.03443 | Acc: 100.000Epoch 010: | Loss: 0.03368 | Acc: 100.000Epoch 011: | Loss: 0.02395 | Acc: 100.000Epoch 012: | Loss: 0.05094 | Acc: 98.250Epoch 013: | Loss: 0.03618 | Acc: 98.250Epoch 014: | Loss: 0.02143 | Acc: 100.000Epoch 015: | Loss: 0.02730 | Acc: 99.500Epoch 016: | Loss: 0.02323 | Acc: 100.000Epoch 017: | Loss: 0.03395 | Acc: 98.250Epoch 018: | Loss: 0.08600 | Acc: 96.750Epoch 019: | Loss: 0.02394 | Acc: 100.000Epoch 020: | Loss: 0.02363 | Acc: 100.000Epoch 021: | Loss: 0.01660 | Acc: 100.000Epoch 022: | Loss: 0.05766 | Acc: 96.750Epoch 023: | Loss: 0.02115 | Acc: 100.000Epoch 024: | Loss: 0.01331 | Acc: 100.000Epoch 025: | Loss: 0.01504 | Acc: 100.000Epoch 026: | Loss: 0.01727 | Acc: 100.000Epoch 027: | Loss: 0.02128 | Acc: 100.000Epoch 028: | Loss: 0.01106 | Acc: 100.000Epoch 029: | Loss: 0.05802 | Acc: 98.250Epoch 030: | Loss: 0.01275 | Acc: 100.000Epoch 031: | Loss: 0.01272 | Acc: 100.000Epoch 032: | Loss: 0.01949 | Acc: 100.000Epoch 033: | Loss: 0.02848 | Acc: 100.000Epoch 034: | Loss: 0.01514 | Acc: 100.000Epoch 035: | Loss: 0.02949 | Acc: 100.000Epoch 036: | Loss: 0.00895 | Acc: 100.000Epoch 037: | Loss: 0.01692 | Acc: 100.000Epoch 038: | Loss: 0.01678 | Acc: 100.000Epoch 039: | Loss: 0.02755 | Acc: 100.000Epoch 040: | Loss: 0.02021 | Acc: 100.000Epoch 041: | Loss: 0.07972 | Acc: 98.250Epoch 042: | Loss: 0.01421 | Acc: 100.000Epoch 043: | Loss: 0.01558 | Acc: 100.000Epoch 044: | Loss: 0.01185 | Acc: 100.000Epoch 045: | Loss: 0.01830 | Acc: 100.000Epoch 046: | Loss: 0.01367 | Acc: 100.000Epoch 047: | Loss: 0.00880 | Acc: 100.000Epoch 048: | Loss: 0.01046 | Acc: 100.000Epoch 049: | Loss: 0.00933 | Acc: 100.000Epoch 050: | Loss: 0.11034 | Acc: 98.250" }, { "code": null, "e": 11818, "s": 11532, "text": "After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad() which reduces memory usage and speeds up computation." }, { "code": null, "e": 11951, "s": 11818, "text": "We start by defining a list that will hold our predictions. Then we loop through our batches using the test_loader. For each batch —" }, { "code": null, "e": 12000, "s": 11951, "text": "We make the predictions using our trained model." }, { "code": null, "e": 12039, "s": 12000, "text": "Round off the probabilities to 1 or 0." }, { "code": null, "e": 12079, "s": 12039, "text": "Move the batch to the GPU from the CPU." }, { "code": null, "e": 12143, "s": 12079, "text": "Convert the tensor to a numpy object and append it to our list." }, { "code": null, "e": 12246, "s": 12143, "text": "Flatten out the list so that we can use it as an input to confusion_matrix and classification_report ." }, { "code": null, "e": 12601, "s": 12246, "text": "y_pred_list = []model.eval()with torch.no_grad(): for X_batch in test_loader: X_batch = X_batch.to(device) y_test_pred = model(X_batch) y_test_pred = torch.sigmoid(y_test_pred) y_pred_tag = torch.round(y_test_pred) y_pred_list.append(y_pred_tag.cpu().numpy())y_pred_list = [a.squeeze().tolist() for a in y_pred_list]" }, { "code": null, "e": 12727, "s": 12601, "text": "Once we have all our predictions, we use the confusion_matrix() function from scikit-learn to calculate the confusion matrix." }, { "code": null, "e": 12850, "s": 12727, "text": "confusion_matrix(y_test, y_pred_list)###################### OUTPUT ######################array([[23, 8], [12, 60]])" }, { "code": null, "e": 12973, "s": 12850, "text": "To obtain the classification report which has precision, recall, and F1 score, we use the function classification_report ." }, { "code": null, "e": 13379, "s": 12973, "text": "print(classification_report(y_test, y_pred_list))###################### OUTPUT ######################precision recall f1-score support 0 0.66 0.74 0.70 31 1 0.88 0.83 0.86 72 accuracy 0.81 103 macro avg 0.77 0.79 0.78 103weighted avg 0.81 0.81 0.81 103" }, { "code": null, "e": 13457, "s": 13379, "text": "Thank you for reading. Suggestions and constructive criticism are welcome. :)" }, { "code": null, "e": 13558, "s": 13457, "text": "This blogpost is a part of the series —” How to train you Neural Net”. You can find the series here." } ]
Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n - GeeksforGeeks
03 Nov, 2021 Given a positive number n, count all distinct Non-Negative Integer pairs (x, y) that satisfy the inequality x*x + y*y < n. Examples: Input: n = 5 Output: 6 The pairs are (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2) Input: n = 6 Output: 8 The pairs are (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2), (1, 2), (2, 1) A Simple Solution is to run two loops. The outer loop goes for all possible values of x (from 0 to √n). The inner loops pick all possible values of y for the current value of x (picked by outer loop). Following is the implementation of a simple solution. C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // This function counts number of pairs (x, y) that satisfy// the inequality x*x + y*y < n.int countSolutions(int n){ int res = 0; for (int x = 0; x*x < n; x++) for (int y = 0; x*x + y*y < n; y++) res++; return res;} // Driver program to test above functionint main(){ cout << "Total Number of distinct Non-Negative pairs is " << countSolutions(6) << endl; return 0;} // Java code to Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// inequality x*x + y*y < nimport java.io.*; class GFG{ // This function counts number // of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int res = 0; for (int x = 0; x * x < n; x++) for (int y = 0; x * x + y * y < n; y++) res++; return res; } // Driver program public static void main(String args[]) { System.out.println ( "Total Number of distinct Non-Negative pairs is " +countSolutions(6)); }} // This article is contributed by vt_m. # Python3 implementation of above approach # This function counts number of pairs# (x, y) that satisfy# the inequality x*x + y*y < n.def countSolutions(n): res = 0 x = 0 while(x * x < n): y = 0 while(x * x + y * y < n): res = res + 1 y = y + 1 x = x + 1 return res # Driver program to test above functionif __name__=='__main__': print("Total Number of distinct Non-Negative pairs is ", countSolutions(6)) # This code is contributed by# Sanjit_Prasad // C# code to Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// inequality x*x + y*y < nusing System; class GFG { // This function counts number // of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int res = 0; for (int x = 0; x*x < n; x++) for (int y = 0; x*x + y*y < n; y++) res++; return res; } // Driver program public static void Main() { Console.WriteLine( "Total Number of " + "distinct Non-Negative pairs is " + countSolutions(6)); }} // This code is contributed by Sam007. <?php// PHP program Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// Inequality x*x + y*y < n // function counts number of// pairs (x, y) that satisfy// the inequality x*x + y*y < n.function countSolutions($n){ $res = 0; for($x = 0; $x * $x < $n; $x++) for($y = 0; $x * $x + $y * $y < $n; $y++) $res++; return $res;} // Driver Code{ echo "Total Number of distinct Non-Negative pairs is "; echo countSolutions(6) ; return 0;} // This code is contributed by nitin mittal.?> <script> // This function counts number// of pairs (x, y) that satisfy// the inequality x*x + y*y < n. function countSolutions( n){ let res = 0; for (let x = 0; x*x < n; x++){ for (let y = 0; x*x + y*y < n; y++){ res++; } } return res;} // Driver program to test above functiondocument.write("Total Number of distinct Non-Negative pairs is "+countSolutions(6)); </script> Output: Total Number of distinct Non-Negative pairs is 8 An upper bound for the time complexity of the above solution is O(n). The outer loop runs √n times. The inner loop runs at most √n times. Auxiliary Space: O(1) Using an Efficient Solution, we can find the count in O(√n) time. The idea is to first find the count of all y values corresponding to the 0 value of x. Let count of distinct y values be yCount. We can find yCount by running a loop and comparing yCount*yCount with n. After we have the initial yCount, we can one by one increase the value of x and find the next value of yCount by reducing yCount. C++ Java Python3 C# PHP Javascript // An efficient C program to find different (x, y) pairs that// satisfy x*x + y*y < n.#include <iostream>using namespace std; // This function counts number of pairs (x, y) that satisfy// the inequality x*x + y*y < n.int countSolutions(int n){ int x = 0, yCount, res = 0; // Find the count of different y values for x = 0. for (yCount = 0; yCount*yCount < n; yCount++) ; // One by one increase value of x, and find yCount for // current x. If yCount becomes 0, then we have reached // maximum possible value of x. while (yCount != 0) { // Add yCount (count of different possible values of y // for current x) to result res += yCount; // Increment x x++; // Update yCount for current x. Keep reducing yCount while // the inequality is not satisfied. while (yCount != 0 && (x*x + (yCount-1)*(yCount-1) >= n)) yCount--; } return res;} // Driver program to test above functionint main(){ cout << "Total Number of distinct Non-Negative pairs is " << countSolutions(6) << endl; return 0;} // An efficient Java program to// find different (x, y) pairs// that satisfy x*x + y*y < n.import java.io.*; class GFG{ // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have reached // maximum possible value of x. while (yCount != 0) { // Add yCount (count of different possible // values of y for current x) to result res += yCount; // Increment x x++; // Update yCount for current x. Keep reducing // yCount while the inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } // Driver program public static void main(String args[]) { System.out.println ( "Total Number of distinct Non-Negative pairs is " +countSolutions(6)) ; }} // This article is contributed by vt_m. # An efficient python program to# find different (x, y) pairs# that satisfy x*x + y*y < n. # This function counts number of# pairs (x, y) that satisfy the# inequality x*x + y*y < n.def countSolutions(n): x = 0 res = 0 yCount = 0 # Find the count of different # y values for x = 0. while(yCount * yCount < n): yCount = yCount + 1 # One by one increase value of # x, and find yCount for current # x. If yCount becomes 0, then # we have reached maximum # possible value of x. while (yCount != 0): # Add yCount (count of # different possible values # of y for current x) to # result res = res + yCount # Increment x x = x + 1 # Update yCount for current # x. Keep reducing yCount # while the inequality is # not satisfied. while (yCount != 0 and (x * x + (yCount - 1) * (yCount - 1) >= n)): yCount = yCount - 1 return res # Driver program to test# above functionprint ("Total Number of distinct ", "Non-Negative pairs is " , countSolutions(6)) # This code is contributed by Sam007. // An efficient C# program to// find different (x, y) pairs// that satisfy x*x + y*y < n.using System; class GFG { // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have // reached maximum possible value // of x. while (yCount != 0) { // Add yCount (count of different // possible values of y for // current x) to result res += yCount; // Increment x x++; // Update yCount for current x. // Keep reducing yCount while the // inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } // Driver program public static void Main() { Console.WriteLine( "Total Number of " + "distinct Non-Negative pairs is " + countSolutions(6)) ; }} // This code is contributed by Sam007. <?php// An efficient C program to find different// (x, y) pairs that satisfy x*x + y*y < n. // This function counts number of pairs// (x, y) that satisfy the inequality// x*x + y*y < n.function countSolutions( $n){ $x = 0; $yCount; $res = 0; // Find the count of different y values // for x = 0. for ($yCount = 0; $yCount*$yCount < $n; $yCount++) ; // One by one increase value of x, and // find yCount for current x. If yCount // becomes 0, then we have reached // maximum possible value of x. while ($yCount != 0) { // Add yCount (count of different // possible values of y // for current x) to result $res += $yCount; // Increment x $x++; // Update yCount for current x. Keep // reducing yCount while the // inequality is not satisfied. while ($yCount != 0 and ($x * $x + ($yCount-1) * ($yCount-1) >= $n)) $yCount--; } return $res;} // Driver program to test above functionecho "Total Number of distinct Non-Negative", "pairs is ", countSolutions(6) ,"\n"; // This code is contributed by anuj_67.?> <script> // An efficient Javascript program to // find different (x, y) pairs // that satisfy x*x + y*y < n. // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. function countSolutions(n) { let x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have // reached maximum possible value // of x. while (yCount != 0) { // Add yCount (count of different // possible values of y for // current x) to result res += yCount; // Increment x x++; // Update yCount for current x. // Keep reducing yCount while the // inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } document.write( "Total Number of " + "distinct Non-Negative pairs is " + countSolutions(6)) ; </script> Output: Total Number of distinct Non-Negative pairs is 8 Time Complexity of the above solution seems more but if we take a closer look, we can see that it is O(√n). In every step inside the inner loop, the value of yCount is decremented by 1. The value yCount can decrement at most O(√n) times as yCount is counted y values for x = 0. In the outer loop, the value of x is incremented. The value of x can also increment at most O(√n) times as the last x is for yCount equals 1. Auxiliary Space: O(1)This article is contributed by Sachin Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 nitin mittal vt_m Sanjit_Prasad rohitsingh07052 vaibhavrabadiya117 souravmahato348 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) How to check if a given point lies inside or outside a polygon? Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space
[ { "code": null, "e": 26071, "s": 26043, "text": "\n03 Nov, 2021" }, { "code": null, "e": 26195, "s": 26071, "text": "Given a positive number n, count all distinct Non-Negative Integer pairs (x, y) that satisfy the inequality x*x + y*y < n. " }, { "code": null, "e": 26205, "s": 26195, "text": "Examples:" }, { "code": null, "e": 26405, "s": 26205, "text": "Input: n = 5\nOutput: 6\nThe pairs are (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2)\n\nInput: n = 6\nOutput: 8\nThe pairs are (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2),\n (1, 2), (2, 1)" }, { "code": null, "e": 26607, "s": 26405, "text": "A Simple Solution is to run two loops. The outer loop goes for all possible values of x (from 0 to √n). The inner loops pick all possible values of y for the current value of x (picked by outer loop). " }, { "code": null, "e": 26663, "s": 26607, "text": "Following is the implementation of a simple solution. " }, { "code": null, "e": 26667, "s": 26663, "text": "C++" }, { "code": null, "e": 26672, "s": 26667, "text": "Java" }, { "code": null, "e": 26680, "s": 26672, "text": "Python3" }, { "code": null, "e": 26683, "s": 26680, "text": "C#" }, { "code": null, "e": 26687, "s": 26683, "text": "PHP" }, { "code": null, "e": 26698, "s": 26687, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // This function counts number of pairs (x, y) that satisfy// the inequality x*x + y*y < n.int countSolutions(int n){ int res = 0; for (int x = 0; x*x < n; x++) for (int y = 0; x*x + y*y < n; y++) res++; return res;} // Driver program to test above functionint main(){ cout << \"Total Number of distinct Non-Negative pairs is \" << countSolutions(6) << endl; return 0;}", "e": 27139, "s": 26698, "text": null }, { "code": "// Java code to Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// inequality x*x + y*y < nimport java.io.*; class GFG{ // This function counts number // of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int res = 0; for (int x = 0; x * x < n; x++) for (int y = 0; x * x + y * y < n; y++) res++; return res; } // Driver program public static void main(String args[]) { System.out.println ( \"Total Number of distinct Non-Negative pairs is \" +countSolutions(6)); }} // This article is contributed by vt_m.", "e": 27877, "s": 27139, "text": null }, { "code": "# Python3 implementation of above approach # This function counts number of pairs# (x, y) that satisfy# the inequality x*x + y*y < n.def countSolutions(n): res = 0 x = 0 while(x * x < n): y = 0 while(x * x + y * y < n): res = res + 1 y = y + 1 x = x + 1 return res # Driver program to test above functionif __name__=='__main__': print(\"Total Number of distinct Non-Negative pairs is \", countSolutions(6)) # This code is contributed by# Sanjit_Prasad", "e": 28395, "s": 27877, "text": null }, { "code": "// C# code to Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// inequality x*x + y*y < nusing System; class GFG { // This function counts number // of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int res = 0; for (int x = 0; x*x < n; x++) for (int y = 0; x*x + y*y < n; y++) res++; return res; } // Driver program public static void Main() { Console.WriteLine( \"Total Number of \" + \"distinct Non-Negative pairs is \" + countSolutions(6)); }} // This code is contributed by Sam007.", "e": 29094, "s": 28395, "text": null }, { "code": "<?php// PHP program Count Distinct// Non-Negative Integer Pairs// (x, y) that Satisfy the// Inequality x*x + y*y < n // function counts number of// pairs (x, y) that satisfy// the inequality x*x + y*y < n.function countSolutions($n){ $res = 0; for($x = 0; $x * $x < $n; $x++) for($y = 0; $x * $x + $y * $y < $n; $y++) $res++; return $res;} // Driver Code{ echo \"Total Number of distinct Non-Negative pairs is \"; echo countSolutions(6) ; return 0;} // This code is contributed by nitin mittal.?>", "e": 29625, "s": 29094, "text": null }, { "code": "<script> // This function counts number// of pairs (x, y) that satisfy// the inequality x*x + y*y < n. function countSolutions( n){ let res = 0; for (let x = 0; x*x < n; x++){ for (let y = 0; x*x + y*y < n; y++){ res++; } } return res;} // Driver program to test above functiondocument.write(\"Total Number of distinct Non-Negative pairs is \"+countSolutions(6)); </script>", "e": 30023, "s": 29625, "text": null }, { "code": null, "e": 30032, "s": 30023, "text": "Output: " }, { "code": null, "e": 30081, "s": 30032, "text": "Total Number of distinct Non-Negative pairs is 8" }, { "code": null, "e": 30220, "s": 30081, "text": "An upper bound for the time complexity of the above solution is O(n). The outer loop runs √n times. The inner loop runs at most √n times. " }, { "code": null, "e": 30243, "s": 30220, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 30643, "s": 30243, "text": "Using an Efficient Solution, we can find the count in O(√n) time. The idea is to first find the count of all y values corresponding to the 0 value of x. Let count of distinct y values be yCount. We can find yCount by running a loop and comparing yCount*yCount with n. After we have the initial yCount, we can one by one increase the value of x and find the next value of yCount by reducing yCount. " }, { "code": null, "e": 30647, "s": 30643, "text": "C++" }, { "code": null, "e": 30652, "s": 30647, "text": "Java" }, { "code": null, "e": 30660, "s": 30652, "text": "Python3" }, { "code": null, "e": 30663, "s": 30660, "text": "C#" }, { "code": null, "e": 30667, "s": 30663, "text": "PHP" }, { "code": null, "e": 30678, "s": 30667, "text": "Javascript" }, { "code": "// An efficient C program to find different (x, y) pairs that// satisfy x*x + y*y < n.#include <iostream>using namespace std; // This function counts number of pairs (x, y) that satisfy// the inequality x*x + y*y < n.int countSolutions(int n){ int x = 0, yCount, res = 0; // Find the count of different y values for x = 0. for (yCount = 0; yCount*yCount < n; yCount++) ; // One by one increase value of x, and find yCount for // current x. If yCount becomes 0, then we have reached // maximum possible value of x. while (yCount != 0) { // Add yCount (count of different possible values of y // for current x) to result res += yCount; // Increment x x++; // Update yCount for current x. Keep reducing yCount while // the inequality is not satisfied. while (yCount != 0 && (x*x + (yCount-1)*(yCount-1) >= n)) yCount--; } return res;} // Driver program to test above functionint main(){ cout << \"Total Number of distinct Non-Negative pairs is \" << countSolutions(6) << endl; return 0;}", "e": 31759, "s": 30678, "text": null }, { "code": "// An efficient Java program to// find different (x, y) pairs// that satisfy x*x + y*y < n.import java.io.*; class GFG{ // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have reached // maximum possible value of x. while (yCount != 0) { // Add yCount (count of different possible // values of y for current x) to result res += yCount; // Increment x x++; // Update yCount for current x. Keep reducing // yCount while the inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } // Driver program public static void main(String args[]) { System.out.println ( \"Total Number of distinct Non-Negative pairs is \" +countSolutions(6)) ; }} // This article is contributed by vt_m.", "e": 33169, "s": 31759, "text": null }, { "code": "# An efficient python program to# find different (x, y) pairs# that satisfy x*x + y*y < n. # This function counts number of# pairs (x, y) that satisfy the# inequality x*x + y*y < n.def countSolutions(n): x = 0 res = 0 yCount = 0 # Find the count of different # y values for x = 0. while(yCount * yCount < n): yCount = yCount + 1 # One by one increase value of # x, and find yCount for current # x. If yCount becomes 0, then # we have reached maximum # possible value of x. while (yCount != 0): # Add yCount (count of # different possible values # of y for current x) to # result res = res + yCount # Increment x x = x + 1 # Update yCount for current # x. Keep reducing yCount # while the inequality is # not satisfied. while (yCount != 0 and (x * x + (yCount - 1) * (yCount - 1) >= n)): yCount = yCount - 1 return res # Driver program to test# above functionprint (\"Total Number of distinct \", \"Non-Negative pairs is \" , countSolutions(6)) # This code is contributed by Sam007.", "e": 34378, "s": 33169, "text": null }, { "code": "// An efficient C# program to// find different (x, y) pairs// that satisfy x*x + y*y < n.using System; class GFG { // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. static int countSolutions(int n) { int x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have // reached maximum possible value // of x. while (yCount != 0) { // Add yCount (count of different // possible values of y for // current x) to result res += yCount; // Increment x x++; // Update yCount for current x. // Keep reducing yCount while the // inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } // Driver program public static void Main() { Console.WriteLine( \"Total Number of \" + \"distinct Non-Negative pairs is \" + countSolutions(6)) ; }} // This code is contributed by Sam007.", "e": 35862, "s": 34378, "text": null }, { "code": "<?php// An efficient C program to find different// (x, y) pairs that satisfy x*x + y*y < n. // This function counts number of pairs// (x, y) that satisfy the inequality// x*x + y*y < n.function countSolutions( $n){ $x = 0; $yCount; $res = 0; // Find the count of different y values // for x = 0. for ($yCount = 0; $yCount*$yCount < $n; $yCount++) ; // One by one increase value of x, and // find yCount for current x. If yCount // becomes 0, then we have reached // maximum possible value of x. while ($yCount != 0) { // Add yCount (count of different // possible values of y // for current x) to result $res += $yCount; // Increment x $x++; // Update yCount for current x. Keep // reducing yCount while the // inequality is not satisfied. while ($yCount != 0 and ($x * $x + ($yCount-1) * ($yCount-1) >= $n)) $yCount--; } return $res;} // Driver program to test above functionecho \"Total Number of distinct Non-Negative\", \"pairs is \", countSolutions(6) ,\"\\n\"; // This code is contributed by anuj_67.?>", "e": 37053, "s": 35862, "text": null }, { "code": "<script> // An efficient Javascript program to // find different (x, y) pairs // that satisfy x*x + y*y < n. // This function counts number //of pairs (x, y) that satisfy // the inequality x*x + y*y < n. function countSolutions(n) { let x = 0, yCount, res = 0; // Find the count of different // y values for x = 0. for (yCount = 0; yCount * yCount < n; yCount++) ; // One by one increase value of x, // and find yCount forcurrent x. If // yCount becomes 0, then we have // reached maximum possible value // of x. while (yCount != 0) { // Add yCount (count of different // possible values of y for // current x) to result res += yCount; // Increment x x++; // Update yCount for current x. // Keep reducing yCount while the // inequality is not satisfied. while (yCount != 0 && (x * x + (yCount - 1) * (yCount - 1) >= n)) yCount--; } return res; } document.write( \"Total Number of \" + \"distinct Non-Negative pairs is \" + countSolutions(6)) ; </script>", "e": 38443, "s": 37053, "text": null }, { "code": null, "e": 38452, "s": 38443, "text": "Output: " }, { "code": null, "e": 38501, "s": 38452, "text": "Total Number of distinct Non-Negative pairs is 8" }, { "code": null, "e": 38922, "s": 38501, "text": "Time Complexity of the above solution seems more but if we take a closer look, we can see that it is O(√n). In every step inside the inner loop, the value of yCount is decremented by 1. The value yCount can decrement at most O(√n) times as yCount is counted y values for x = 0. In the outer loop, the value of x is incremented. The value of x can also increment at most O(√n) times as the last x is for yCount equals 1. " }, { "code": null, "e": 39115, "s": 38922, "text": "Auxiliary Space: O(1)This article is contributed by Sachin Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39122, "s": 39115, "text": "Sam007" }, { "code": null, "e": 39135, "s": 39122, "text": "nitin mittal" }, { "code": null, "e": 39140, "s": 39135, "text": "vt_m" }, { "code": null, "e": 39154, "s": 39140, "text": "Sanjit_Prasad" }, { "code": null, "e": 39170, "s": 39154, "text": "rohitsingh07052" }, { "code": null, "e": 39189, "s": 39170, "text": "vaibhavrabadiya117" }, { "code": null, "e": 39205, "s": 39189, "text": "souravmahato348" }, { "code": null, "e": 39218, "s": 39205, "text": "Mathematical" }, { "code": null, "e": 39231, "s": 39218, "text": "Mathematical" }, { "code": null, "e": 39329, "s": 39231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39373, "s": 39329, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 39404, "s": 39373, "text": "Modular multiplicative inverse" }, { "code": null, "e": 39429, "s": 39404, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 39464, "s": 39429, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 39496, "s": 39464, "text": "Check if a number is Palindrome" }, { "code": null, "e": 39538, "s": 39496, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 39602, "s": 39538, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 39635, "s": 39602, "text": "Program to multiply two matrices" }, { "code": null, "e": 39670, "s": 39635, "text": "Count ways to reach the n'th stair" } ]
Create empty DataFrame with only column names in R - GeeksforGeeks
05 Apr, 2021 In this article, we are going to create an empty data frame with column names in the R programming language. The basic syntax for creating a data frame is using data.frame(). Syntax: data.frame(input_data,nrow,ncol) Parameter: input_data may be values ot list or vector. nrow specifies the number of rows ncol specifies the number of columns. Steps – Create an empty dataframe Define the column names to a variable Assign that variable to the dataframe. Display data frame so created We can assign column names to dataframe by using colnames() Syntax: colnames(dataframe_name) Given below is the implementation using the above approach. Example 1: R # created vector with 5 characterscolumns= c("id","names","address","phone","aadhar no") # pass this vector length to ncol parameter# and nrow with 0myData = data.frame(matrix(nrow = 0, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData) Output: [1] id names address phone aadhar no <0 rows> (or 0-length row.names) If we specify nrow parameter with morethan 0, it will take NA as that many rows. Example 2: R # created vector with 5 characterscolumns= c("id","names","address","phone","aadhar no") # pass this vector length to ncol parameter # and nrow with 1myData = data.frame(matrix(nrow=1, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData) # pass this vector length to ncol parameter and # nrow with 6myData = data.frame(matrix(nrow=6, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData) Output: id names address phone aadhar no 1 NA NA NA NA NA id names address phone aadhar no 1 NA NA NA NA NA 2 NA NA NA NA NA 3 NA NA NA NA NA 4 NA NA NA NA NA 5 NA NA NA NA NA 6 NA NA NA NA NA Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Logistic Regression in R Programming How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n05 Apr, 2021" }, { "code": null, "e": 25351, "s": 25242, "text": "In this article, we are going to create an empty data frame with column names in the R programming language." }, { "code": null, "e": 25417, "s": 25351, "text": "The basic syntax for creating a data frame is using data.frame()." }, { "code": null, "e": 25458, "s": 25417, "text": "Syntax: data.frame(input_data,nrow,ncol)" }, { "code": null, "e": 25469, "s": 25458, "text": "Parameter:" }, { "code": null, "e": 25513, "s": 25469, "text": "input_data may be values ot list or vector." }, { "code": null, "e": 25547, "s": 25513, "text": "nrow specifies the number of rows" }, { "code": null, "e": 25585, "s": 25547, "text": "ncol specifies the number of columns." }, { "code": null, "e": 25593, "s": 25585, "text": "Steps –" }, { "code": null, "e": 25619, "s": 25593, "text": "Create an empty dataframe" }, { "code": null, "e": 25657, "s": 25619, "text": "Define the column names to a variable" }, { "code": null, "e": 25696, "s": 25657, "text": "Assign that variable to the dataframe." }, { "code": null, "e": 25726, "s": 25696, "text": "Display data frame so created" }, { "code": null, "e": 25786, "s": 25726, "text": "We can assign column names to dataframe by using colnames()" }, { "code": null, "e": 25794, "s": 25786, "text": "Syntax:" }, { "code": null, "e": 25819, "s": 25794, "text": "colnames(dataframe_name)" }, { "code": null, "e": 25879, "s": 25819, "text": "Given below is the implementation using the above approach." }, { "code": null, "e": 25890, "s": 25879, "text": "Example 1:" }, { "code": null, "e": 25892, "s": 25890, "text": "R" }, { "code": "# created vector with 5 characterscolumns= c(\"id\",\"names\",\"address\",\"phone\",\"aadhar no\") # pass this vector length to ncol parameter# and nrow with 0myData = data.frame(matrix(nrow = 0, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData)", "e": 26179, "s": 25892, "text": null }, { "code": null, "e": 26187, "s": 26179, "text": "Output:" }, { "code": null, "e": 26241, "s": 26187, "text": "[1] id names address phone aadhar no" }, { "code": null, "e": 26274, "s": 26241, "text": "<0 rows> (or 0-length row.names)" }, { "code": null, "e": 26355, "s": 26274, "text": "If we specify nrow parameter with morethan 0, it will take NA as that many rows." }, { "code": null, "e": 26366, "s": 26355, "text": "Example 2:" }, { "code": null, "e": 26368, "s": 26366, "text": "R" }, { "code": "# created vector with 5 characterscolumns= c(\"id\",\"names\",\"address\",\"phone\",\"aadhar no\") # pass this vector length to ncol parameter # and nrow with 1myData = data.frame(matrix(nrow=1, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData) # pass this vector length to ncol parameter and # nrow with 6myData = data.frame(matrix(nrow=6, ncol = length(columns))) # assign column namescolnames(myData) = columns # displayprint(myData)", "e": 26850, "s": 26368, "text": null }, { "code": null, "e": 26858, "s": 26850, "text": "Output:" }, { "code": null, "e": 26893, "s": 26858, "text": " id names address phone aadhar no" }, { "code": null, "e": 26928, "s": 26893, "text": "1 NA NA NA NA NA" }, { "code": null, "e": 26963, "s": 26928, "text": " id names address phone aadhar no" }, { "code": null, "e": 26998, "s": 26963, "text": "1 NA NA NA NA NA" }, { "code": null, "e": 27033, "s": 26998, "text": "2 NA NA NA NA NA" }, { "code": null, "e": 27068, "s": 27033, "text": "3 NA NA NA NA NA" }, { "code": null, "e": 27103, "s": 27068, "text": "4 NA NA NA NA NA" }, { "code": null, "e": 27138, "s": 27103, "text": "5 NA NA NA NA NA" }, { "code": null, "e": 27173, "s": 27138, "text": "6 NA NA NA NA NA" }, { "code": null, "e": 27180, "s": 27173, "text": "Picked" }, { "code": null, "e": 27201, "s": 27180, "text": "R DataFrame-Programs" }, { "code": null, "e": 27213, "s": 27201, "text": "R-DataFrame" }, { "code": null, "e": 27224, "s": 27213, "text": "R Language" }, { "code": null, "e": 27235, "s": 27224, "text": "R Programs" }, { "code": null, "e": 27333, "s": 27235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27342, "s": 27333, "text": "Comments" }, { "code": null, "e": 27355, "s": 27342, "text": "Old Comments" }, { "code": null, "e": 27407, "s": 27355, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27445, "s": 27407, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27480, "s": 27445, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27538, "s": 27480, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27575, "s": 27538, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27633, "s": 27575, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27682, "s": 27633, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27732, "s": 27682, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27775, "s": 27732, "text": "Replace Specific Characters in String in R" } ]
How to create a collapsible section using CSS and JavaScript ? - GeeksforGeeks
30 Jun, 2020 Collapsible sections are sections of content that can shrink and expand by clicking on them. They are a popular way to organize content in such a manner that the user will be able to see the content of a section only if he wishes. In this article, we will learn how to create a simple collapsible section using CSS and JavaScript. It is done by using a button and enclosing the content of the section in a div. The event listener is added to the button to listen to mouse clicks. The “Active” class is toggled on each button click. When the section is expanded, the background color of the button changes. Also, the “display” property of the content is changed to “block” on click button event to make it visible when it is “none” (hidden) and vice versa as shown below. Example 1: <!DOCTYPE html><html><style> .collapse { background-color: #a2de96; border: none; outline: none; font-size: 25px; } .active, .collapse:hover { background-color: #438a5e; } .text { background-color: #e1ffc2; display: none; font-size: 20px; }</style> <body> <h1>GeeksforGeeks</h1> <button type="button" class="collapse"> Open Collapsible section </button> <div class="text"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </div> <script> var btn = document.getElementsByClassName("collapse"); btn[0].addEventListener("click", function () { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); </script></body> </html> Output: Collapsed: Expanded: Example 2: The “width” of the collapse button and the content is set to 50% and the content is “center” aligned. <!DOCTYPE html><html> <head><style> .collapse { background-color: #a2de96; border: none; outline: none; font-size: 25px; } .active, .collapse:hover { background-color: #438a5e; } .text { background-color: #e1ffc2; display: none; font-size: 20px; }</style></head> <body> <h1>GeeksforGeeks</h1> <button type="button" class="collapse"> Open Collapsible section </button> <div class="text"> How to create a collapsible section using CSS and JavaScript? </div> <script> var btn = document .getElementsByClassName("collapse"); btn[0].addEventListener("click", function () { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); </script></body> </html> Output: Collapsed: Expanded: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 27085, "s": 27057, "text": "\n30 Jun, 2020" }, { "code": null, "e": 27416, "s": 27085, "text": "Collapsible sections are sections of content that can shrink and expand by clicking on them. They are a popular way to organize content in such a manner that the user will be able to see the content of a section only if he wishes. In this article, we will learn how to create a simple collapsible section using CSS and JavaScript." }, { "code": null, "e": 27856, "s": 27416, "text": "It is done by using a button and enclosing the content of the section in a div. The event listener is added to the button to listen to mouse clicks. The “Active” class is toggled on each button click. When the section is expanded, the background color of the button changes. Also, the “display” property of the content is changed to “block” on click button event to make it visible when it is “none” (hidden) and vice versa as shown below." }, { "code": null, "e": 27867, "s": 27856, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html><style> .collapse { background-color: #a2de96; border: none; outline: none; font-size: 25px; } .active, .collapse:hover { background-color: #438a5e; } .text { background-color: #e1ffc2; display: none; font-size: 20px; }</style> <body> <h1>GeeksforGeeks</h1> <button type=\"button\" class=\"collapse\"> Open Collapsible section </button> <div class=\"text\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </div> <script> var btn = document.getElementsByClassName(\"collapse\"); btn[0].addEventListener(\"click\", function () { this.classList.toggle(\"active\"); var content = this.nextElementSibling; if (content.style.display === \"block\") { content.style.display = \"none\"; } else { content.style.display = \"block\"; } }); </script></body> </html>", "e": 29001, "s": 27867, "text": null }, { "code": null, "e": 29009, "s": 29001, "text": "Output:" }, { "code": null, "e": 29020, "s": 29009, "text": "Collapsed:" }, { "code": null, "e": 29030, "s": 29020, "text": "Expanded:" }, { "code": null, "e": 29143, "s": 29030, "text": "Example 2: The “width” of the collapse button and the content is set to 50% and the content is “center” aligned." }, { "code": "<!DOCTYPE html><html> <head><style> .collapse { background-color: #a2de96; border: none; outline: none; font-size: 25px; } .active, .collapse:hover { background-color: #438a5e; } .text { background-color: #e1ffc2; display: none; font-size: 20px; }</style></head> <body> <h1>GeeksforGeeks</h1> <button type=\"button\" class=\"collapse\"> Open Collapsible section </button> <div class=\"text\"> How to create a collapsible section using CSS and JavaScript? </div> <script> var btn = document .getElementsByClassName(\"collapse\"); btn[0].addEventListener(\"click\", function () { this.classList.toggle(\"active\"); var content = this.nextElementSibling; if (content.style.display === \"block\") { content.style.display = \"none\"; } else { content.style.display = \"block\"; } }); </script></body> </html> ", "e": 30205, "s": 29143, "text": null }, { "code": null, "e": 30213, "s": 30205, "text": "Output:" }, { "code": null, "e": 30224, "s": 30213, "text": "Collapsed:" }, { "code": null, "e": 30234, "s": 30224, "text": "Expanded:" }, { "code": null, "e": 30243, "s": 30234, "text": "CSS-Misc" }, { "code": null, "e": 30253, "s": 30243, "text": "HTML-Misc" }, { "code": null, "e": 30269, "s": 30253, "text": "JavaScript-Misc" }, { "code": null, "e": 30273, "s": 30269, "text": "CSS" }, { "code": null, "e": 30278, "s": 30273, "text": "HTML" }, { "code": null, "e": 30289, "s": 30278, "text": "JavaScript" }, { "code": null, "e": 30306, "s": 30289, "text": "Web Technologies" }, { "code": null, "e": 30311, "s": 30306, "text": "HTML" }, { "code": null, "e": 30409, "s": 30311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30464, "s": 30409, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30503, "s": 30464, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30540, "s": 30503, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30601, "s": 30540, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30642, "s": 30601, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 30702, "s": 30642, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30763, "s": 30702, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30787, "s": 30763, "text": "REST API (Introduction)" }, { "code": null, "e": 30828, "s": 30787, "text": "HTML Cheat Sheet - A Basic Guide to HTML" } ]
Explain the visibility of global variables in imported modules in Python?
Globals in Python are global to a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it. import module1 module1.a=3 On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it: global_module.py module1.py: import global_module def fun(): print global_module.var Other files: import global_module import module1 global_module.var = 3 module1.fun()
[ { "code": null, "e": 1371, "s": 1062, "text": "Globals in Python are global to a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it." }, { "code": null, "e": 1398, "s": 1371, "text": "import module1\nmodule1.a=3" }, { "code": null, "e": 1511, "s": 1398, "text": "On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:" }, { "code": null, "e": 1685, "s": 1511, "text": "global_module.py\nmodule1.py:\nimport global_module\ndef fun():\n print global_module.var\nOther files:\nimport global_module\nimport module1\nglobal_module.var = 3\nmodule1.fun()" } ]
AWK - Control Flow
Like other programming languages, AWK provides conditional statements to control the flow of a program. This chapter explains AWK's control statements with suitable examples. It simply tests the condition and performs certain actions depending upon the condition. Given below is the syntax of if statement − if (condition) action We can also use a pair of curly braces as given below to execute multiple actions − if (condition) { action-1 action-1 . . action-n } For instance, the following example checks whether a number is even or not − [jerry]$ awk 'BEGIN {num = 10; if (num % 2 == 0) printf "%d is even number.\n", num }' On executing the above code, you get the following result − 10 is even number. In if-else syntax, we can provide a list of actions to be performed when a condition becomes false. The syntax of if-else statement is as follows − if (condition) action-1 else action-2 In the above syntax, action-1 is performed when the condition evaluates to true and action-2 is performed when the condition evaluates to false. For instance, the following example checks whether a number is even or not − [jerry]$ awk 'BEGIN { num = 11; if (num % 2 == 0) printf "%d is even number.\n", num; else printf "%d is odd number.\n", num }' On executing this code, you get the following result − 11 is odd number. We can easily create an if-else-if ladder by using multiple if-else statements. The following example demonstrates this − [jerry]$ awk 'BEGIN { a = 30; if (a==10) print "a = 10"; else if (a == 20) print "a = 20"; else if (a == 30) print "a = 30"; }' On executing this code, you get the following result − a = 30 Print Add Notes Bookmark this page
[ { "code": null, "e": 2032, "s": 1857, "text": "Like other programming languages, AWK provides conditional statements to control the flow of a program. This chapter explains AWK's control statements with suitable examples." }, { "code": null, "e": 2165, "s": 2032, "text": "It simply tests the condition and performs certain actions depending upon the condition. Given below is the syntax of if statement −" }, { "code": null, "e": 2191, "s": 2165, "text": "if (condition)\n action\n" }, { "code": null, "e": 2275, "s": 2191, "text": "We can also use a pair of curly braces as given below to execute multiple actions −" }, { "code": null, "e": 2341, "s": 2275, "text": "if (condition) {\n action-1\n action-1\n .\n .\n action-n\n}\n" }, { "code": null, "e": 2418, "s": 2341, "text": "For instance, the following example checks whether a number is even or not −" }, { "code": null, "e": 2505, "s": 2418, "text": "[jerry]$ awk 'BEGIN {num = 10; if (num % 2 == 0) printf \"%d is even number.\\n\", num }'" }, { "code": null, "e": 2565, "s": 2505, "text": "On executing the above code, you get the following result −" }, { "code": null, "e": 2585, "s": 2565, "text": "10 is even number.\n" }, { "code": null, "e": 2685, "s": 2585, "text": "In if-else syntax, we can provide a list of actions to be performed when a condition becomes false." }, { "code": null, "e": 2733, "s": 2685, "text": "The syntax of if-else statement is as follows −" }, { "code": null, "e": 2778, "s": 2733, "text": "if (condition)\n action-1\nelse\n action-2\n" }, { "code": null, "e": 3000, "s": 2778, "text": "In the above syntax, action-1 is performed when the condition evaluates to true and action-2 is performed when the condition evaluates to false. For instance, the following example checks whether a number is even or not −" }, { "code": null, "e": 3139, "s": 3000, "text": "[jerry]$ awk 'BEGIN {\n num = 11; if (num % 2 == 0) printf \"%d is even number.\\n\", num; \n else printf \"%d is odd number.\\n\", num \n}'" }, { "code": null, "e": 3194, "s": 3139, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3213, "s": 3194, "text": "11 is odd number.\n" }, { "code": null, "e": 3335, "s": 3213, "text": "We can easily create an if-else-if ladder by using multiple if-else statements. The following example demonstrates this −" }, { "code": null, "e": 3488, "s": 3335, "text": "[jerry]$ awk 'BEGIN {\n a = 30;\n \n if (a==10)\n print \"a = 10\";\n else if (a == 20)\n print \"a = 20\";\n else if (a == 30)\n print \"a = 30\";\n}'" }, { "code": null, "e": 3543, "s": 3488, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3551, "s": 3543, "text": "a = 30\n" }, { "code": null, "e": 3558, "s": 3551, "text": " Print" }, { "code": null, "e": 3569, "s": 3558, "text": " Add Notes" } ]
Difference between Java and JavaScript - GeeksforGeeks
26 Nov, 2021 In this article, we will know about Java & Javascript, & also see the significant distinction between Java & Javascript. JavaScript:JavaScript is a lightweight programming language(“scripting language”) and is used to make web pages interactive. It can insert dynamic text into HTML. JavaScript is also known as the browser’s language. JavaScript(JS) is not similar or related to Java. Both the languages have a C-like syntax and are widely used in client-side and server-side Web applications, but there are few similarities only. Features of Javascript: JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static, after JS was created dynamic Web sites were made. Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions. Can handle date and time. Performs Form Validation although the forms are created using HTML. No compiler is needed. Example: This is the basic Javascript example. HTML <script> console.log("Welcome to GeeksforGeeks Learning");</script> Output: Welcome to GeeksforGeeks Learning Java:Java is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. Features of Java: Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class. There are 4 pillars of OOP’s concept:AbstractionEncapsulationInheritancePolymorphism Abstraction Encapsulation Inheritance Polymorphism Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation. Robust: Java language is robust that means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. Secure: In java, we don’t have pointers, and so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Example: This is the basic Java program. Java import java.io.*; class GFG { public static void main(String[] args) { System.out.println( "Welcome to GeeksforGeeks Learning"); }} Output: Welcome to GeeksforGeeks Learning Difference between Java and JavaScript: pp_pankaj nikunjkr078 bunnyram19 bhaskargeeksforgeeks JavaScript-Misc Difference Between Java JavaScript Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Process and Thread Stack vs Heap Memory Allocation Difference Between Spark DataFrame and Pandas DataFrame Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 24714, "s": 24686, "text": "\n26 Nov, 2021" }, { "code": null, "e": 24835, "s": 24714, "text": "In this article, we will know about Java & Javascript, & also see the significant distinction between Java & Javascript." }, { "code": null, "e": 25246, "s": 24835, "text": "JavaScript:JavaScript is a lightweight programming language(“scripting language”) and is used to make web pages interactive. It can insert dynamic text into HTML. JavaScript is also known as the browser’s language. JavaScript(JS) is not similar or related to Java. Both the languages have a C-like syntax and are widely used in client-side and server-side Web applications, but there are few similarities only." }, { "code": null, "e": 25270, "s": 25246, "text": "Features of Javascript:" }, { "code": null, "e": 25421, "s": 25270, "text": "JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static, after JS was created dynamic Web sites were made." }, { "code": null, "e": 25565, "s": 25421, "text": "Functions in JS are objects. They may have properties and methods just like another object. They can be passed as arguments in other functions." }, { "code": null, "e": 25591, "s": 25565, "text": "Can handle date and time." }, { "code": null, "e": 25659, "s": 25591, "text": "Performs Form Validation although the forms are created using HTML." }, { "code": null, "e": 25682, "s": 25659, "text": "No compiler is needed." }, { "code": null, "e": 25730, "s": 25682, "text": "Example: This is the basic Javascript example. " }, { "code": null, "e": 25735, "s": 25730, "text": "HTML" }, { "code": "<script> console.log(\"Welcome to GeeksforGeeks Learning\");</script>", "e": 25806, "s": 25735, "text": null }, { "code": null, "e": 25814, "s": 25806, "text": "Output:" }, { "code": null, "e": 25848, "s": 25814, "text": "Welcome to GeeksforGeeks Learning" }, { "code": null, "e": 26058, "s": 25848, "text": "Java:Java is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”." }, { "code": null, "e": 26076, "s": 26058, "text": "Features of Java:" }, { "code": null, "e": 26245, "s": 26076, "text": "Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform." }, { "code": null, "e": 26522, "s": 26245, "text": "Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class. There are 4 pillars of OOP’s concept:AbstractionEncapsulationInheritancePolymorphism" }, { "code": null, "e": 26534, "s": 26522, "text": "Abstraction" }, { "code": null, "e": 26548, "s": 26534, "text": "Encapsulation" }, { "code": null, "e": 26560, "s": 26548, "text": "Inheritance" }, { "code": null, "e": 26573, "s": 26560, "text": "Polymorphism" }, { "code": null, "e": 26742, "s": 26573, "text": "Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation." }, { "code": null, "e": 27024, "s": 26742, "text": "Robust: Java language is robust that means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language." }, { "code": null, "e": 27173, "s": 27024, "text": "Secure: In java, we don’t have pointers, and so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so." }, { "code": null, "e": 27370, "s": 27173, "text": "Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java." }, { "code": null, "e": 27536, "s": 27370, "text": "Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU." }, { "code": null, "e": 27577, "s": 27536, "text": "Example: This is the basic Java program." }, { "code": null, "e": 27582, "s": 27577, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { System.out.println( \"Welcome to GeeksforGeeks Learning\"); }}", "e": 27742, "s": 27582, "text": null }, { "code": null, "e": 27750, "s": 27742, "text": "Output:" }, { "code": null, "e": 27784, "s": 27750, "text": "Welcome to GeeksforGeeks Learning" }, { "code": null, "e": 27824, "s": 27784, "text": "Difference between Java and JavaScript:" }, { "code": null, "e": 27834, "s": 27824, "text": "pp_pankaj" }, { "code": null, "e": 27846, "s": 27834, "text": "nikunjkr078" }, { "code": null, "e": 27857, "s": 27846, "text": "bunnyram19" }, { "code": null, "e": 27878, "s": 27857, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27894, "s": 27878, "text": "JavaScript-Misc" }, { "code": null, "e": 27913, "s": 27894, "text": "Difference Between" }, { "code": null, "e": 27918, "s": 27913, "text": "Java" }, { "code": null, "e": 27929, "s": 27918, "text": "JavaScript" }, { "code": null, "e": 27934, "s": 27929, "text": "Java" }, { "code": null, "e": 28032, "s": 27934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28041, "s": 28032, "text": "Comments" }, { "code": null, "e": 28054, "s": 28041, "text": "Old Comments" }, { "code": null, "e": 28092, "s": 28054, "text": "Difference between Process and Thread" }, { "code": null, "e": 28124, "s": 28092, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 28180, "s": 28124, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 28241, "s": 28180, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28309, "s": 28241, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28324, "s": 28309, "text": "Arrays in Java" }, { "code": null, "e": 28368, "s": 28324, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28390, "s": 28368, "text": "For-each loop in Java" }, { "code": null, "e": 28426, "s": 28390, "text": "Arrays.sort() in Java with examples" } ]
jQuery - filter( fn ) Method
The filter( fn ) method filters all elements from the set of matched elements that do not match the specified function. Here is the simple syntax to use this method − selector.filter( selector ) Here is the description of all the parameters used by this method − fn − The function is called with a context equal to the current element just like $.each. If the function returns false, then the element is removed otherwise the element is kept. fn − The function is called with a context equal to the current element just like $.each. If the function returns false, then the element is removed otherwise the element is kept. Following is an example showing a simple usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").filter(function (index) { return index == 1 || $(this).attr("class") == "middle"; }).addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "top">list item 1</li> <li class = "top">list item 2</li> <li class = "middle">list item 3</li> <li class = "middle">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 Following is an example showing a simple usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").filter(function (index) { return index == 1 || $(this).attr("class") == "middle"; }).addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "top">list item 1</li> <li class = "selected">list item 2</li> <li class = "selected">list item 3</li> <li class = "selected">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2442, "s": 2322, "text": "The filter( fn ) method filters all elements from the set of matched elements that do not match the specified function." }, { "code": null, "e": 2489, "s": 2442, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2518, "s": 2489, "text": "selector.filter( selector )\n" }, { "code": null, "e": 2586, "s": 2518, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2766, "s": 2586, "text": "fn − The function is called with a context equal to the current element just like $.each. If the function returns false, then the element is removed otherwise the element is kept." }, { "code": null, "e": 2946, "s": 2766, "text": "fn − The function is called with a context equal to the current element just like $.each. If the function returns false, then the element is removed otherwise the element is kept." }, { "code": null, "e": 3010, "s": 2946, "text": "Following is an example showing a simple usage of this method −" }, { "code": null, "e": 3952, "s": 3010, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").filter(function (index) {\n return index == 1 || $(this).attr(\"class\") == \"middle\";\n }).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"top\">list item 1</li>\n <li class = \"top\">list item 2</li>\n <li class = \"middle\">list item 3</li>\n <li class = \"middle\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3989, "s": 3952, "text": "This will produce following result −" }, { "code": null, "e": 4001, "s": 3989, "text": "list item 1" }, { "code": null, "e": 4013, "s": 4001, "text": "list item 2" }, { "code": null, "e": 4025, "s": 4013, "text": "list item 3" }, { "code": null, "e": 4037, "s": 4025, "text": "list item 4" }, { "code": null, "e": 4049, "s": 4037, "text": "list item 5" }, { "code": null, "e": 4061, "s": 4049, "text": "list item 6" }, { "code": null, "e": 4125, "s": 4061, "text": "Following is an example showing a simple usage of this method −" }, { "code": null, "e": 5076, "s": 4125, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").filter(function (index) {\n return index == 1 || $(this).attr(\"class\") == \"middle\";\n }).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"top\">list item 1</li>\n <li class = \"selected\">list item 2</li>\n <li class = \"selected\">list item 3</li>\n <li class = \"selected\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5113, "s": 5076, "text": "This will produce following result −" }, { "code": null, "e": 5125, "s": 5113, "text": "list item 1" }, { "code": null, "e": 5137, "s": 5125, "text": "list item 2" }, { "code": null, "e": 5149, "s": 5137, "text": "list item 3" }, { "code": null, "e": 5161, "s": 5149, "text": "list item 4" }, { "code": null, "e": 5173, "s": 5161, "text": "list item 5" }, { "code": null, "e": 5185, "s": 5173, "text": "list item 6" }, { "code": null, "e": 5218, "s": 5185, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 5232, "s": 5218, "text": " Mahesh Kumar" }, { "code": null, "e": 5267, "s": 5232, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5281, "s": 5267, "text": " Pratik Singh" }, { "code": null, "e": 5316, "s": 5281, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5333, "s": 5316, "text": " Frahaan Hussain" }, { "code": null, "e": 5366, "s": 5333, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 5394, "s": 5366, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5427, "s": 5394, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5448, "s": 5427, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5480, "s": 5448, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5497, "s": 5480, "text": " Laurence Svekis" }, { "code": null, "e": 5504, "s": 5497, "text": " Print" }, { "code": null, "e": 5515, "s": 5504, "text": " Add Notes" } ]
Email Template using HTML and CSS - GeeksforGeeks
30 Aug, 2019 Have you ever wondered how one can send creative colorful email templates? In this article, we will create a basic email template using HTML and CSS. These email templates are generally designed for marketing purpose and are circulated through email campaigns.The main purpose of sending an email template is to attain the number of Call to Action(CTA). The creative design of an email template engages a client and can get more CTA on the required destination page. Creating a sample TemplateSending the emails according to the desired outline can be very challenging. This is because different browsers possess different configurations and hence different parent CSS properties. For example, the “display: absolute” property does not work while sending an email through Gmail.Similarly, there are few other precautions to be taken when you code an email template. The first and most important step to start with email templates is, One must use HTML tables to build the basic structure of an email template.Creating a table ensures that the content sent is not distorted on forwarding or mailing using different email applications. Example: To start <!-- Create main outline within which email will be enclosed --> <body style="background-color:grey"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="550" bgcolor="white" style="border:2px solid black"> <tbody> <tr> <td align="center"> <br /> <table align="center" border="0" cellpadding="0" cellspacing="0" class="col-550" width="550"> <tbody> <!-- content goes here --> </tbody> </table> </td> </tr> </tbody> </table></body> Now, remember, email applications will support inline style only. If you specify the properties in style tag, the email application will not consider them and the specified properties will not be applied.Example: <body style="background-color:grey"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="550" bgcolor="white" style="border:2px solid black"> <tbody> <tr> <td align="center"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="col-550" width="550"> <tbody> <tr> <td align="center" style="background-color: #4cb96b; height: 50px;"> <a href="#" style="text-decoration: none;"> <p style="color:white;font-weight:bold;"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table></body> Further sections can be made using <tr> and <td>tags. Now, let us enter further information.Example: <!-- Complete Email template --> <body style="background-color:grey"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="550" bgcolor="white" style="border:2px solid black"> <tbody> <tr> <td align="center"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="col-550" width="550"> <tbody> <tr> <td align="center" style="background-color: #4cb96b; height: 50px;"> <a href="#" style="text-decoration: none;"> <p style="color:white; font-weight:bold;"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> <tr style="height: 300px;"> <td align="center" style="border: none; border-bottom: 2px solid #4cb96b; padding-right: 20px;padding-left:20px"> <p style="font-weight: bolder;font-size: 42px; letter-spacing: 0.025em; color:black;"> Hello Geeks! <br> Check out our latest Blogs </p> </td> </tr> <tr style="display: inline-block;"> <td style="height: 150px; padding: 20px; border: none; border-bottom: 2px solid #361B0E; background-color: white;"> <h2 style="text-align: left; align-items: center;"> Design Patterns : A Must Skill to have for Software Developers in 2019 </h2> <p class="data" style="text-align: justify-all; align-items: center; font-size: 15px; padding-bottom: 12px;"> Design Patterns....??? I think you have heard this name before in programming... Yes, you might have heard this name before in programming if you are... </p> <p> <a href="https://www.geeksforgeeks.org/design-patterns-a-must-skill-to-have-for-software-developers-in-2019/" style="text-decoration: none; color:black; border: 2px solid #4cb96b; padding: 10px 30px; font-weight: bold;"> Read More </a> </p> </td> </tr> </tbody> </table></body> Finally, you may add a footer containing social media links, company name, contact information, etc.Example: <!-- Complete Email template --> <body style="background-color:grey"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="550" bgcolor="white" style="border:2px solid black"> <tbody> <tr> <td align="center"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="col-550" width="550"> <tbody> <tr> <td align="center" style="background-color: #4cb96b; height: 50px;"> <a href="#" style="text-decoration: none;"> <p style="color:white; font-weight:bold;"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> <tr style="height: 300px;"> <td align="center" style="border: none; border-bottom: 2px solid #4cb96b; padding-right: 20px;padding-left:20px"> <p style="font-weight: bolder;font-size: 42px; letter-spacing: 0.025em; color:black;"> Hello Geeks! <br> Check out our latest Blogs </p> </td> </tr> <tr style="display: inline-block;"> <td style="height: 150px; padding: 20px; border: none; border-bottom: 2px solid #361B0E; background-color: white;"> <h2 style="text-align: left; align-items: center;"> Design Patterns : A Must Skill to have for Software Developers in 2019 </h2> <p class="data" style="text-align: justify-all; align-items: center; font-size: 15px; padding-bottom: 12px;"> Design Patterns....??? I think you have heard this name before in programming... Yes, you might have heard this name before in programming if you are... </p> <p> <a href="https://www.geeksforgeeks.org/design-patterns-a-must-skill-to-have-for-software-developers-in-2019/" style="text-decoration: none; color:black; border: 2px solid #4cb96b; padding: 10px 30px; font-weight: bold;"> Read More </a> </p> </td> </tr> <tr style="border: none; background-color: #4cb96b; height: 40px; color:white; padding-bottom: 20px; text-align: center;"> <td height="40px" align="center"> <p style="color:white; line-height: 1.5em;"> GeeksforGeeks </p> <a href="#" style="border:none; text-decoration: none; padding: 5px;"> <img height="30" src="https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/icon-twitter_20190610074030.png" width="30" /> </a> <a href="#" style="border:none; text-decoration: none; padding: 5px;"> <img height="30" src="https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/icon-linkedin_20190610074015.png" width="30" /> </a> <a href="#" style="border:none; text-decoration: none; padding: 5px;"> <img height="20" src="https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/facebook-letter-logo_20190610100050.png" width="24" style="position: relative; padding-bottom: 5px;" /> </a></td></tr><tr><td style="font-family:'Open Sans', Arial, sans-serif; font-size:11px; line-height:18px; color:#999999;" valign="top" align="center"><a href="#" target="_blank" style="color:#999999; text-decoration:underline;">PRIVACY STATEMENT</a> | <a href="#" target="_blank" style="color:#999999; text-decoration:underline;">TERMS OF SERVICE</a> | <a href="#" target="_blank" style="color:#999999; text-decoration:underline;">RETURNS</a><br> © 2012 GeeksforGeeks. All Rights Reserved.<br> If you do not wish to receive any further emails from us, please <a href="#" target="_blank" style="text-decoration:none; color:#999999;">unsubscribe</a> </td> </tr> </tbody></table></td> </tr> <tr> <td class="em_hide" style="line-height:1px; min-width:700px; background-color:#ffffff;"> <img alt="" src="images/spacer.gif" style="max-height:1px; min-height:1px; display:block; width:700px; min-width:700px;" width="700" border="0" height="1"> </td> </tr> </tbody> </table></body> Output: In this way, you can create many beautiful templates. While coding email with divs makes it a lot easier and faster, there are a lot of issues if you code using divs. Moreover, coding the structure using table and table rows is easy and fun. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS How to Upload Image into Database and Display it using PHP ? Form validation using jQuery How to set fixed width for <td> in a table ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction)
[ { "code": null, "e": 25158, "s": 25130, "text": "\n30 Aug, 2019" }, { "code": null, "e": 25625, "s": 25158, "text": "Have you ever wondered how one can send creative colorful email templates? In this article, we will create a basic email template using HTML and CSS. These email templates are generally designed for marketing purpose and are circulated through email campaigns.The main purpose of sending an email template is to attain the number of Call to Action(CTA). The creative design of an email template engages a client and can get more CTA on the required destination page." }, { "code": null, "e": 26292, "s": 25625, "text": "Creating a sample TemplateSending the emails according to the desired outline can be very challenging. This is because different browsers possess different configurations and hence different parent CSS properties. For example, the “display: absolute” property does not work while sending an email through Gmail.Similarly, there are few other precautions to be taken when you code an email template. The first and most important step to start with email templates is, One must use HTML tables to build the basic structure of an email template.Creating a table ensures that the content sent is not distorted on forwarding or mailing using different email applications." }, { "code": null, "e": 26310, "s": 26292, "text": "Example: To start" }, { "code": "<!-- Create main outline within which email will be enclosed --> <body style=\"background-color:grey\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" bgcolor=\"white\" style=\"border:2px solid black\"> <tbody> <tr> <td align=\"center\"> <br /> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"col-550\" width=\"550\"> <tbody> <!-- content goes here --> </tbody> </table> </td> </tr> </tbody> </table></body>", "e": 27001, "s": 26310, "text": null }, { "code": null, "e": 27214, "s": 27001, "text": "Now, remember, email applications will support inline style only. If you specify the properties in style tag, the email application will not consider them and the specified properties will not be applied.Example:" }, { "code": "<body style=\"background-color:grey\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" bgcolor=\"white\" style=\"border:2px solid black\"> <tbody> <tr> <td align=\"center\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"col-550\" width=\"550\"> <tbody> <tr> <td align=\"center\" style=\"background-color: #4cb96b; height: 50px;\"> <a href=\"#\" style=\"text-decoration: none;\"> <p style=\"color:white;font-weight:bold;\"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table></body>", "e": 28377, "s": 27214, "text": null }, { "code": null, "e": 28478, "s": 28377, "text": "Further sections can be made using <tr> and <td>tags. Now, let us enter further information.Example:" }, { "code": "<!-- Complete Email template --> <body style=\"background-color:grey\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" bgcolor=\"white\" style=\"border:2px solid black\"> <tbody> <tr> <td align=\"center\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"col-550\" width=\"550\"> <tbody> <tr> <td align=\"center\" style=\"background-color: #4cb96b; height: 50px;\"> <a href=\"#\" style=\"text-decoration: none;\"> <p style=\"color:white; font-weight:bold;\"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> <tr style=\"height: 300px;\"> <td align=\"center\" style=\"border: none; border-bottom: 2px solid #4cb96b; padding-right: 20px;padding-left:20px\"> <p style=\"font-weight: bolder;font-size: 42px; letter-spacing: 0.025em; color:black;\"> Hello Geeks! <br> Check out our latest Blogs </p> </td> </tr> <tr style=\"display: inline-block;\"> <td style=\"height: 150px; padding: 20px; border: none; border-bottom: 2px solid #361B0E; background-color: white;\"> <h2 style=\"text-align: left; align-items: center;\"> Design Patterns : A Must Skill to have for Software Developers in 2019 </h2> <p class=\"data\" style=\"text-align: justify-all; align-items: center; font-size: 15px; padding-bottom: 12px;\"> Design Patterns....??? I think you have heard this name before in programming... Yes, you might have heard this name before in programming if you are... </p> <p> <a href=\"https://www.geeksforgeeks.org/design-patterns-a-must-skill-to-have-for-software-developers-in-2019/\" style=\"text-decoration: none; color:black; border: 2px solid #4cb96b; padding: 10px 30px; font-weight: bold;\"> Read More </a> </p> </td> </tr> </tbody> </table></body>", "e": 31778, "s": 28478, "text": null }, { "code": null, "e": 31887, "s": 31778, "text": "Finally, you may add a footer containing social media links, company name, contact information, etc.Example:" }, { "code": "<!-- Complete Email template --> <body style=\"background-color:grey\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" bgcolor=\"white\" style=\"border:2px solid black\"> <tbody> <tr> <td align=\"center\"> <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"col-550\" width=\"550\"> <tbody> <tr> <td align=\"center\" style=\"background-color: #4cb96b; height: 50px;\"> <a href=\"#\" style=\"text-decoration: none;\"> <p style=\"color:white; font-weight:bold;\"> GeeksforGeeks </p> </a> </td> </tr> </tbody> </table> </td> </tr> <tr style=\"height: 300px;\"> <td align=\"center\" style=\"border: none; border-bottom: 2px solid #4cb96b; padding-right: 20px;padding-left:20px\"> <p style=\"font-weight: bolder;font-size: 42px; letter-spacing: 0.025em; color:black;\"> Hello Geeks! <br> Check out our latest Blogs </p> </td> </tr> <tr style=\"display: inline-block;\"> <td style=\"height: 150px; padding: 20px; border: none; border-bottom: 2px solid #361B0E; background-color: white;\"> <h2 style=\"text-align: left; align-items: center;\"> Design Patterns : A Must Skill to have for Software Developers in 2019 </h2> <p class=\"data\" style=\"text-align: justify-all; align-items: center; font-size: 15px; padding-bottom: 12px;\"> Design Patterns....??? I think you have heard this name before in programming... Yes, you might have heard this name before in programming if you are... </p> <p> <a href=\"https://www.geeksforgeeks.org/design-patterns-a-must-skill-to-have-for-software-developers-in-2019/\" style=\"text-decoration: none; color:black; border: 2px solid #4cb96b; padding: 10px 30px; font-weight: bold;\"> Read More </a> </p> </td> </tr> <tr style=\"border: none; background-color: #4cb96b; height: 40px; color:white; padding-bottom: 20px; text-align: center;\"> <td height=\"40px\" align=\"center\"> <p style=\"color:white; line-height: 1.5em;\"> GeeksforGeeks </p> <a href=\"#\" style=\"border:none; text-decoration: none; padding: 5px;\"> <img height=\"30\" src=\"https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/icon-twitter_20190610074030.png\" width=\"30\" /> </a> <a href=\"#\" style=\"border:none; text-decoration: none; padding: 5px;\"> <img height=\"30\" src=\"https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/icon-linkedin_20190610074015.png\" width=\"30\" /> </a> <a href=\"#\" style=\"border:none; text-decoration: none; padding: 5px;\"> <img height=\"20\" src=\"https://extraaedgeresources.blob.core.windows.net/demo/salesdemo/EmailAttachments/facebook-letter-logo_20190610100050.png\" width=\"24\" style=\"position: relative; padding-bottom: 5px;\" /> </a></td></tr><tr><td style=\"font-family:'Open Sans', Arial, sans-serif; font-size:11px; line-height:18px; color:#999999;\" valign=\"top\" align=\"center\"><a href=\"#\" target=\"_blank\" style=\"color:#999999; text-decoration:underline;\">PRIVACY STATEMENT</a> | <a href=\"#\" target=\"_blank\" style=\"color:#999999; text-decoration:underline;\">TERMS OF SERVICE</a> | <a href=\"#\" target=\"_blank\" style=\"color:#999999; text-decoration:underline;\">RETURNS</a><br> © 2012 GeeksforGeeks. All Rights Reserved.<br> If you do not wish to receive any further emails from us, please <a href=\"#\" target=\"_blank\" style=\"text-decoration:none; color:#999999;\">unsubscribe</a> </td> </tr> </tbody></table></td> </tr> <tr> <td class=\"em_hide\" style=\"line-height:1px; min-width:700px; background-color:#ffffff;\"> <img alt=\"\" src=\"images/spacer.gif\" style=\"max-height:1px; min-height:1px; display:block; width:700px; min-width:700px;\" width=\"700\" border=\"0\" height=\"1\"> </td> </tr> </tbody> </table></body>", "e": 37835, "s": 31887, "text": null }, { "code": null, "e": 37843, "s": 37835, "text": "Output:" }, { "code": null, "e": 38085, "s": 37843, "text": "In this way, you can create many beautiful templates. While coding email with divs makes it a lot easier and faster, there are a lot of issues if you code using divs. Moreover, coding the structure using table and table rows is easy and fun." }, { "code": null, "e": 38222, "s": 38085, "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": 38226, "s": 38222, "text": "CSS" }, { "code": null, "e": 38231, "s": 38226, "text": "HTML" }, { "code": null, "e": 38248, "s": 38231, "text": "Web Technologies" }, { "code": null, "e": 38275, "s": 38248, "text": "Web technologies Questions" }, { "code": null, "e": 38280, "s": 38275, "text": "HTML" }, { "code": null, "e": 38378, "s": 38280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38387, "s": 38378, "text": "Comments" }, { "code": null, "e": 38400, "s": 38387, "text": "Old Comments" }, { "code": null, "e": 38437, "s": 38400, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 38478, "s": 38437, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 38539, "s": 38478, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 38568, "s": 38539, "text": "Form validation using jQuery" }, { "code": null, "e": 38613, "s": 38568, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 38673, "s": 38613, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 38734, "s": 38673, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 38784, "s": 38734, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 38837, "s": 38784, "text": "Hide or show elements in HTML using display property" } ]
How to change the Entry Widget Value with a Scale in Tkinter?
Tkinter Entry widget is an input widget that supports only single-line user input. It accepts all the characters in the text field unless or until there are no restrictions set for the input. We can change the value of the Entry widget with the help of the Scale widget. The Scale widget contains a lower value and a threshold that limits the user to adjust the value in a particular range. To update the value in the Entry widget while updating the value of Scale widget, we have to create a variable that has to be given to both the scale and the entry widget. #Import the Tkinter Library from tkinter import * from tkinter import ttk #Create an instance of Tkinter Frame win = Tk() #Set the geometry of window win.geometry("700x350") #Create an Integer Variable to set the initial value of Scale var = IntVar(value=10) #Create an Entry widget entry = ttk.Entry(win,width= 45,textvariable=var) scale = Scale(win, from_=10, to=200, width= 20, orient="horizontal", variable=var) entry.place(relx= .5, rely= .5, anchor= CENTER) scale.place(relx= .5, rely= .6, anchor = CENTER) win.mainloop() Running the above code will display an Entry widget and a Scale which can be used to update the value in the Entry widget.
[ { "code": null, "e": 1453, "s": 1062, "text": "Tkinter Entry widget is an input widget that supports only single-line user input. It accepts all the characters in the text field unless or until there are no restrictions set for the input. We can change the value of the Entry widget with the help of the Scale widget. The Scale widget contains a lower value and a threshold that limits the user to adjust the value in a particular range." }, { "code": null, "e": 1625, "s": 1453, "text": "To update the value in the Entry widget while updating the value of Scale widget, we have to create a variable that has to be given to both the scale and the entry widget." }, { "code": null, "e": 2159, "s": 1625, "text": "#Import the Tkinter Library\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry of window\nwin.geometry(\"700x350\")\n\n#Create an Integer Variable to set the initial value of Scale\nvar = IntVar(value=10)\n\n#Create an Entry widget\nentry = ttk.Entry(win,width= 45,textvariable=var)\nscale = Scale(win, from_=10, to=200, width= 20, orient=\"horizontal\", variable=var)\n\nentry.place(relx= .5, rely= .5, anchor= CENTER)\nscale.place(relx= .5, rely= .6, anchor = CENTER)\n\nwin.mainloop()" }, { "code": null, "e": 2282, "s": 2159, "text": "Running the above code will display an Entry widget and a Scale which can be used to update the value in the Entry widget." } ]
How to make a 4D plot with Matplotlib using arbitrary data?
To make a 4D plot, we can create x, y, z and c standard data points. Create a new figure or activate an existing figure. Use figure() method to create a figure or activate an existing figure. Use figure() method to create a figure or activate an existing figure. Add a figure as part of a subplot arrangement. Add a figure as part of a subplot arrangement. Create x, y, z and c data points using numpy. Create x, y, z and c data points using numpy. Create a scatter plot using scatter method. Create a scatter plot using scatter method. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = np.random.standard_normal(100) y = np.random.standard_normal(100) z = np.random.standard_normal(100) c = np.random.standard_normal(100) img = ax.scatter(x, y, z, c=c, cmap='YlOrRd', alpha=1) plt.show()
[ { "code": null, "e": 1183, "s": 1062, "text": "To make a 4D plot, we can create x, y, z and c standard data points. Create a new figure or activate an existing figure." }, { "code": null, "e": 1254, "s": 1183, "text": "Use figure() method to create a figure or activate an existing figure." }, { "code": null, "e": 1325, "s": 1254, "text": "Use figure() method to create a figure or activate an existing figure." }, { "code": null, "e": 1372, "s": 1325, "text": "Add a figure as part of a subplot arrangement." }, { "code": null, "e": 1419, "s": 1372, "text": "Add a figure as part of a subplot arrangement." }, { "code": null, "e": 1465, "s": 1419, "text": "Create x, y, z and c data points using numpy." }, { "code": null, "e": 1511, "s": 1465, "text": "Create x, y, z and c data points using numpy." }, { "code": null, "e": 1555, "s": 1511, "text": "Create a scatter plot using scatter method." }, { "code": null, "e": 1599, "s": 1555, "text": "Create a scatter plot using scatter method." }, { "code": null, "e": 1641, "s": 1599, "text": "To display the figure, use show() method." }, { "code": null, "e": 1683, "s": 1641, "text": "To display the figure, use show() method." }, { "code": null, "e": 2094, "s": 1683, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nx = np.random.standard_normal(100)\ny = np.random.standard_normal(100)\nz = np.random.standard_normal(100)\nc = np.random.standard_normal(100)\nimg = ax.scatter(x, y, z, c=c, cmap='YlOrRd', alpha=1)\nplt.show()" } ]
GATE | GATE CS 2011 | Question 65 - GeeksforGeeks
22 Jul, 2021 Consider the following table of arrival time and burst time for three processes P0, P1 and P2. Process Arrival time Burst Time P0 0 ms 9 ms P1 1 ms 4 ms P2 2 ms 9 ms The pre-emptive shortest job first scheduling algorithm is used. Scheduling is carried out only at arrival or completion of processes. What is the average waiting time for the three processes?(A) 5.0 ms(B) 4.33 ms(C) 6.33(D) 7.33Answer: (A)Explanation: See Question 4 of https://www.geeksforgeeks.org/operating-systems-set-6/ Watch GeeksforGeeks Video Explanation : YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0017:10 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2011 GATE-GATE CS 2011 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24218, "s": 24190, "text": "\n22 Jul, 2021" }, { "code": null, "e": 24313, "s": 24218, "text": "Consider the following table of arrival time and burst time for three processes P0, P1 and P2." }, { "code": null, "e": 24448, "s": 24313, "text": "Process Arrival time Burst Time\nP0 0 ms 9 ms\nP1 1 ms 4 ms\nP2 2 ms 9 ms" }, { "code": null, "e": 24774, "s": 24448, "text": "The pre-emptive shortest job first scheduling algorithm is used. Scheduling is carried out only at arrival or completion of processes. What is the average waiting time for the three processes?(A) 5.0 ms(B) 4.33 ms(C) 6.33(D) 7.33Answer: (A)Explanation: See Question 4 of https://www.geeksforgeeks.org/operating-systems-set-6/" }, { "code": null, "e": 24814, "s": 24774, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 25705, "s": 24814, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0017:10 / 39:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=y1BbjvO_xog\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25718, "s": 25705, "text": "GATE-CS-2011" }, { "code": null, "e": 25736, "s": 25718, "text": "GATE-GATE CS 2011" }, { "code": null, "e": 25741, "s": 25736, "text": "GATE" }, { "code": null, "e": 25839, "s": 25741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25848, "s": 25839, "text": "Comments" }, { "code": null, "e": 25861, "s": 25848, "text": "Old Comments" }, { "code": null, "e": 25895, "s": 25861, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25928, "s": 25895, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25970, "s": 25928, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26012, "s": 25970, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26054, "s": 26012, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26088, "s": 26054, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26122, "s": 26088, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26164, "s": 26122, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26206, "s": 26164, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" } ]
How to Change or Set System Locales in Linux? - GeeksforGeeks
26 Mar, 2021 Locale is basically a set of environmental variables that defines the user’s language, region, and any special variant preferences that the user wants to see in their Linux interface. System libraries and locale-aware applications on the system use these environmental variables. Locale settings usually consist of at least a language code, a country/region code, time/date format, numbers format setting, currency format setting, Color setting, etc. Here we will see how to set/change or view the system’s locale in Linux. For viewing the information regarding the currently installed locale use the following command on the terminal:- $ locale We will get a list of variables that can be reset to a different value according to our choice later on. The current status can be seen using the following command: localectl status We can also view more information about a specific variable that we saw when we run the locale command, for example, LC_TIME, which stores the time and date format, LC_PAPER which stores the paper size settings, LC_TELEPHONE which stores telephone settings format, etc. You can get this information by using the following commands:- $ locale -k LC_TIME $ locale -k LC_TELEPHONE $ locale -k LC_PAPER Display a list of all available locales using the following command:- $ locale -a We might want to change or set the system local, for that we have to use the update-locale program. The LANG variable allows us to set up the locale for the entire system. For setting up LANG to en_IN.UTF-8 and removes definitions for LANGUAGE we can use the following command:- $ sudo update-locale LANG=LANG=en_IN.UTF-8 LANGUAGE OR $ sudo localectl set-locale LANG=en_IN.UTF-8 We can find global locale settings in /etc/default/locale on Ubuntu/Debian Linux distros that you can edit for configuring your system locale manually using the following command:- $ sudo vi /etc/default/locale We can also change the value of a locale that is preset, by editing the .bashrc profile by using the following command:- sudo nano ~/.bashrc We can set a global locale for a single user, by adding the following lines at the end of the ~/.bash_profile file LANG="en_IN.utf8" export LANG If you want to get more information about the System locale, update-locale and localectl just view the manual pages using the following command:- $ man locale $ man update-locale $ man localectl 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 and Setup Spring Boot Project in Eclipse IDE? 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": 26748, "s": 26720, "text": "\n26 Mar, 2021" }, { "code": null, "e": 27028, "s": 26748, "text": "Locale is basically a set of environmental variables that defines the user’s language, region, and any special variant preferences that the user wants to see in their Linux interface. System libraries and locale-aware applications on the system use these environmental variables." }, { "code": null, "e": 27272, "s": 27028, "text": "Locale settings usually consist of at least a language code, a country/region code, time/date format, numbers format setting, currency format setting, Color setting, etc. Here we will see how to set/change or view the system’s locale in Linux." }, { "code": null, "e": 27385, "s": 27272, "text": "For viewing the information regarding the currently installed locale use the following command on the terminal:-" }, { "code": null, "e": 27394, "s": 27385, "text": "$ locale" }, { "code": null, "e": 27499, "s": 27394, "text": "We will get a list of variables that can be reset to a different value according to our choice later on." }, { "code": null, "e": 27559, "s": 27499, "text": "The current status can be seen using the following command:" }, { "code": null, "e": 27576, "s": 27559, "text": "localectl status" }, { "code": null, "e": 27846, "s": 27576, "text": "We can also view more information about a specific variable that we saw when we run the locale command, for example, LC_TIME, which stores the time and date format, LC_PAPER which stores the paper size settings, LC_TELEPHONE which stores telephone settings format, etc." }, { "code": null, "e": 27909, "s": 27846, "text": "You can get this information by using the following commands:-" }, { "code": null, "e": 27977, "s": 27909, "text": "$ locale -k LC_TIME\n$ locale -k LC_TELEPHONE\n$ locale -k LC_PAPER " }, { "code": null, "e": 28048, "s": 27977, "text": " Display a list of all available locales using the following command:-" }, { "code": null, "e": 28060, "s": 28048, "text": "$ locale -a" }, { "code": null, "e": 28232, "s": 28060, "text": "We might want to change or set the system local, for that we have to use the update-locale program. The LANG variable allows us to set up the locale for the entire system." }, { "code": null, "e": 28339, "s": 28232, "text": "For setting up LANG to en_IN.UTF-8 and removes definitions for LANGUAGE we can use the following command:-" }, { "code": null, "e": 28439, "s": 28339, "text": "$ sudo update-locale LANG=LANG=en_IN.UTF-8 LANGUAGE\nOR\n$ sudo localectl set-locale LANG=en_IN.UTF-8" }, { "code": null, "e": 28620, "s": 28439, "text": "We can find global locale settings in /etc/default/locale on Ubuntu/Debian Linux distros that you can edit for configuring your system locale manually using the following command:-" }, { "code": null, "e": 28651, "s": 28620, "text": "$ sudo vi /etc/default/locale" }, { "code": null, "e": 28772, "s": 28651, "text": "We can also change the value of a locale that is preset, by editing the .bashrc profile by using the following command:-" }, { "code": null, "e": 28792, "s": 28772, "text": "sudo nano ~/.bashrc" }, { "code": null, "e": 28909, "s": 28792, "text": "We can set a global locale for a single user, by adding the following lines at the end of the ~/.bash_profile file " }, { "code": null, "e": 28939, "s": 28909, "text": "LANG=\"en_IN.utf8\"\nexport LANG" }, { "code": null, "e": 29085, "s": 28939, "text": "If you want to get more information about the System locale, update-locale and localectl just view the manual pages using the following command:-" }, { "code": null, "e": 29134, "s": 29085, "text": "$ man locale\n$ man update-locale\n$ man localectl" }, { "code": null, "e": 29141, "s": 29134, "text": "Picked" }, { "code": null, "e": 29148, "s": 29141, "text": "How To" }, { "code": null, "e": 29159, "s": 29148, "text": "Linux-Unix" }, { "code": null, "e": 29257, "s": 29159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29291, "s": 29257, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29349, "s": 29291, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29398, "s": 29349, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29458, "s": 29398, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29500, "s": 29458, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29540, "s": 29500, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 29580, "s": 29540, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 29607, "s": 29580, "text": "grep command in Unix/Linux" }, { "code": null, "e": 29642, "s": 29607, "text": "cut command in Linux with examples" } ]
Python | Set Background Template in kivy - GeeksforGeeks
10 Feb, 2020 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Setting a good background template is a good thing to make your app look more attractive to the user. For inserting a background template in your App some modifications need to be done in the .kv file. Below is the code to set a background template for your app. # Program to create a background template for the App # import necessary modules from kivyfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.app import App # create a background class which inherits the boxlayout classclass Background(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) pass # Create App class with name of your appclass SampleApp(App): # return the Window having the background template. def build(self): return Background() # run app in the main functionif __name__ == '__main__': SampleApp().run() .kv file <Background>: id: main_win orientation: "vertical" spacing: 10 space_x: self.size[0]/3 canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: source:'back.jfif' size: root.width, root.height pos: self.pos Button: text: "Click Me" pos_hint :{'center_x':0.2, 'center_y':0.2} size_hint: .30, 0 background_color: (0.06, .36, .4, .675) font_size: 40 Output: Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n10 Feb, 2020" }, { "code": null, "e": 25883, "s": 25647, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 26146, "s": 25883, "text": "Setting a good background template is a good thing to make your app look more attractive to the user. For inserting a background template in your App some modifications need to be done in the .kv file. Below is the code to set a background template for your app." }, { "code": "# Program to create a background template for the App # import necessary modules from kivyfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.app import App # create a background class which inherits the boxlayout classclass Background(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) pass # Create App class with name of your appclass SampleApp(App): # return the Window having the background template. def build(self): return Background() # run app in the main functionif __name__ == '__main__': SampleApp().run()", "e": 26711, "s": 26146, "text": null }, { "code": null, "e": 26720, "s": 26711, "text": ".kv file" }, { "code": "<Background>: id: main_win orientation: \"vertical\" spacing: 10 space_x: self.size[0]/3 canvas.before: Color: rgba: (1, 1, 1, 1) Rectangle: source:'back.jfif' size: root.width, root.height pos: self.pos Button: text: \"Click Me\" pos_hint :{'center_x':0.2, 'center_y':0.2} size_hint: .30, 0 background_color: (0.06, .36, .4, .675) font_size: 40", "e": 27177, "s": 26720, "text": null }, { "code": null, "e": 27185, "s": 27177, "text": "Output:" }, { "code": null, "e": 27196, "s": 27185, "text": "Python-gui" }, { "code": null, "e": 27208, "s": 27196, "text": "Python-kivy" }, { "code": null, "e": 27215, "s": 27208, "text": "Python" }, { "code": null, "e": 27313, "s": 27215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27345, "s": 27313, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27387, "s": 27345, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27429, "s": 27387, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27485, "s": 27429, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27512, "s": 27485, "text": "Python Classes and Objects" }, { "code": null, "e": 27543, "s": 27512, "text": "Python | os.path.join() method" }, { "code": null, "e": 27572, "s": 27543, "text": "Create a directory in Python" }, { "code": null, "e": 27594, "s": 27572, "text": "Defaultdict in Python" }, { "code": null, "e": 27630, "s": 27594, "text": "Python | Pandas dataframe.groupby()" } ]
Find last digit in factorial - GeeksforGeeks
26 Feb, 2021 Given a number n, we need to find the last digit in factorial n. Input : n = 4Output : 44! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4. Input : n = 5Output : 55! = 5*4 * 3 * 2 * 1. = 120. Last digit of 120 is 0. A Naive Solution is to first compute fact = n!, then return the last digit of the result by doing fact % 10. This solution is inefficient and causes integer overflow for even slightly large value of n. An Efficient Solution is based on the observation that all factorials after 5 have 0 as last digit. 1! = 12! = 23! = 64! = 245! = 1206! = 720.............. C++ Java Python3 C# Javascript // C++ program to find last digit in// factorial n.#include <iostream>using namespace std; int lastDigitFactorial(unsigned int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than 4 // the last digit is 0 else return 0;} int main() { cout<<lastDigitFactorial(6); return 0;} // Java program to find last // digit in factorial n.import java.io.*;import java.util.*; class GFG { static int lastDigitFactorial(int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than // 4 the last digit is 0 else return 0;} // Driver codepublic static void main(String[] args){ System.out.println(lastDigitFactorial(6));}} // This code is contributed by coder001 # Python3 program to find last digit in# factorial n. def lastDigitFactorial(n): # Explicitly handle all numbers # less than or equal to 4 if (n == 0): return 1 elif (n <= 2): return n elif (n == 3): return 6 elif (n == 4): return 4 # For all numbers greater than 4 # the last digit is 0 else: return 0 print(lastDigitFactorial(6)) # This code is contributed by divyeshrabadiya07 // C# program to find last// digit in factorial n.using System;class GFG{ static int lastDigitFactorial(int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than // 4 the last digit is 0 else return 0;} // Driver codepublic static void Main(string[] args){ Console.Write(lastDigitFactorial(6));}} // This code is contributed by rutvik_56 <script> // JavaScript program to find last digit in// factorial n. function lastDigitFactorial(n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than 4 // the last digit is 0 else return 0;} // Driver code document.write(lastDigitFactorial(6)); // This code is contributed by Surbhi Tyagi </script> 0 Time Complexity : O(1)Auxiliary Space : O(1) Now try below problems 1) Last non-zero digit in factorial2) Count zeroes in factorial3) First digit in Factorial coder001 divyeshrabadiya07 rutvik_56 surbhityagi15 factorial number-digits Mathematical School Programming Mathematical factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25070, "s": 25042, "text": "\n26 Feb, 2021" }, { "code": null, "e": 25135, "s": 25070, "text": "Given a number n, we need to find the last digit in factorial n." }, { "code": null, "e": 25209, "s": 25135, "text": "Input : n = 4Output : 44! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4." }, { "code": null, "e": 25287, "s": 25209, "text": "Input : n = 5Output : 55! = 5*4 * 3 * 2 * 1. = 120. Last digit of 120 is 0." }, { "code": null, "e": 25490, "s": 25287, "text": "A Naive Solution is to first compute fact = n!, then return the last digit of the result by doing fact % 10. This solution is inefficient and causes integer overflow for even slightly large value of n." }, { "code": null, "e": 25590, "s": 25490, "text": "An Efficient Solution is based on the observation that all factorials after 5 have 0 as last digit." }, { "code": null, "e": 25646, "s": 25590, "text": "1! = 12! = 23! = 64! = 245! = 1206! = 720.............." }, { "code": null, "e": 25650, "s": 25646, "text": "C++" }, { "code": null, "e": 25655, "s": 25650, "text": "Java" }, { "code": null, "e": 25663, "s": 25655, "text": "Python3" }, { "code": null, "e": 25666, "s": 25663, "text": "C#" }, { "code": null, "e": 25677, "s": 25666, "text": "Javascript" }, { "code": "// C++ program to find last digit in// factorial n.#include <iostream>using namespace std; int lastDigitFactorial(unsigned int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than 4 // the last digit is 0 else return 0;} int main() { cout<<lastDigitFactorial(6); return 0;}", "e": 26125, "s": 25677, "text": null }, { "code": "// Java program to find last // digit in factorial n.import java.io.*;import java.util.*; class GFG { static int lastDigitFactorial(int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than // 4 the last digit is 0 else return 0;} // Driver codepublic static void main(String[] args){ System.out.println(lastDigitFactorial(6));}} // This code is contributed by coder001", "e": 26684, "s": 26125, "text": null }, { "code": "# Python3 program to find last digit in# factorial n. def lastDigitFactorial(n): # Explicitly handle all numbers # less than or equal to 4 if (n == 0): return 1 elif (n <= 2): return n elif (n == 3): return 6 elif (n == 4): return 4 # For all numbers greater than 4 # the last digit is 0 else: return 0 print(lastDigitFactorial(6)) # This code is contributed by divyeshrabadiya07", "e": 27101, "s": 26684, "text": null }, { "code": "// C# program to find last// digit in factorial n.using System;class GFG{ static int lastDigitFactorial(int n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than // 4 the last digit is 0 else return 0;} // Driver codepublic static void Main(string[] args){ Console.Write(lastDigitFactorial(6));}} // This code is contributed by rutvik_56", "e": 27628, "s": 27101, "text": null }, { "code": "<script> // JavaScript program to find last digit in// factorial n. function lastDigitFactorial(n){ // Explicitly handle all numbers // less than or equal to 4 if (n == 0) return 1; else if (n <= 2) return n; else if (n == 3) return 6; else if (n == 4) return 4; // For all numbers greater than 4 // the last digit is 0 else return 0;} // Driver code document.write(lastDigitFactorial(6)); // This code is contributed by Surbhi Tyagi </script>", "e": 28116, "s": 27628, "text": null }, { "code": null, "e": 28118, "s": 28116, "text": "0" }, { "code": null, "e": 28165, "s": 28120, "text": "Time Complexity : O(1)Auxiliary Space : O(1)" }, { "code": null, "e": 28188, "s": 28165, "text": "Now try below problems" }, { "code": null, "e": 28279, "s": 28188, "text": "1) Last non-zero digit in factorial2) Count zeroes in factorial3) First digit in Factorial" }, { "code": null, "e": 28288, "s": 28279, "text": "coder001" }, { "code": null, "e": 28306, "s": 28288, "text": "divyeshrabadiya07" }, { "code": null, "e": 28316, "s": 28306, "text": "rutvik_56" }, { "code": null, "e": 28330, "s": 28316, "text": "surbhityagi15" }, { "code": null, "e": 28340, "s": 28330, "text": "factorial" }, { "code": null, "e": 28354, "s": 28340, "text": "number-digits" }, { "code": null, "e": 28367, "s": 28354, "text": "Mathematical" }, { "code": null, "e": 28386, "s": 28367, "text": "School Programming" }, { "code": null, "e": 28399, "s": 28386, "text": "Mathematical" }, { "code": null, "e": 28409, "s": 28399, "text": "factorial" }, { "code": null, "e": 28507, "s": 28409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28516, "s": 28507, "text": "Comments" }, { "code": null, "e": 28529, "s": 28516, "text": "Old Comments" }, { "code": null, "e": 28572, "s": 28529, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 28614, "s": 28572, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 28638, "s": 28614, "text": "Merge two sorted arrays" }, { "code": null, "e": 28652, "s": 28638, "text": "Prime Numbers" }, { "code": null, "e": 28701, "s": 28652, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28719, "s": 28701, "text": "Python Dictionary" }, { "code": null, "e": 28735, "s": 28719, "text": "Arrays in C/C++" }, { "code": null, "e": 28754, "s": 28735, "text": "Inheritance in C++" }, { "code": null, "e": 28779, "s": 28754, "text": "Reverse a string in Java" } ]
JavaScript SyntaxError - Missing ; before statement - GeeksforGeeks
24 Jul, 2020 This JavaScript exception missing ; before statement occurs if there is a semicolon (;) missing in script. Message: SyntaxError: Expected ';' (Edge) SyntaxError: missing ; before statement (Firefox) Error Type: SyntaxError Cause of Error: Somewhere in code, there is a missing semicolon (;). You need to provide it so that JavaScript can parse the source code without any error. Example 1: In this example, the string is not escaped properly and JavaScript expecting a “;”, so the error has occurred. HTML <!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> // invalid string var GFG = 'This is GFG's platform'; document.write(GFG); </script></body></html> Output(In console of Edge Browser): SyntaxError: Expected ';' Example 2: In this example, the properties of an object is declared with the var declaration, Which is invalid. So the error has occurred, HTML <!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var GFG = {}; var GFG.prop_1 = 'Val_1'; document.write(JSON.stringify(GFG)); </script></body></html> Output(In console of Edge Browser): SyntaxError: Expected ';' JavaScript-Errors 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": 26655, "s": 26627, "text": "\n24 Jul, 2020" }, { "code": null, "e": 26762, "s": 26655, "text": "This JavaScript exception missing ; before statement occurs if there is a semicolon (;) missing in script." }, { "code": null, "e": 26771, "s": 26762, "text": "Message:" }, { "code": null, "e": 26855, "s": 26771, "text": "SyntaxError: Expected ';' (Edge)\nSyntaxError: missing ; before statement (Firefox)\n" }, { "code": null, "e": 26867, "s": 26855, "text": "Error Type:" }, { "code": null, "e": 26880, "s": 26867, "text": "SyntaxError\n" }, { "code": null, "e": 27036, "s": 26880, "text": "Cause of Error: Somewhere in code, there is a missing semicolon (;). You need to provide it so that JavaScript can parse the source code without any error." }, { "code": null, "e": 27158, "s": 27036, "text": "Example 1: In this example, the string is not escaped properly and JavaScript expecting a “;”, so the error has occurred." }, { "code": null, "e": 27163, "s": 27158, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> // invalid string var GFG = 'This is GFG's platform'; document.write(GFG); </script></body></html>", "e": 27372, "s": 27163, "text": null }, { "code": null, "e": 27408, "s": 27372, "text": "Output(In console of Edge Browser):" }, { "code": null, "e": 27435, "s": 27408, "text": "SyntaxError: Expected ';'\n" }, { "code": null, "e": 27575, "s": 27435, "text": "Example 2: In this example, the properties of an object is declared with the var declaration, Which is invalid. So the error has occurred, " }, { "code": null, "e": 27580, "s": 27575, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> var GFG = {}; var GFG.prop_1 = 'Val_1'; document.write(JSON.stringify(GFG)); </script></body></html>", "e": 27791, "s": 27580, "text": null }, { "code": null, "e": 27828, "s": 27791, "text": "Output(In console of Edge Browser): " }, { "code": null, "e": 27855, "s": 27828, "text": "SyntaxError: Expected ';'\n" }, { "code": null, "e": 27873, "s": 27855, "text": "JavaScript-Errors" }, { "code": null, "e": 27884, "s": 27873, "text": "JavaScript" }, { "code": null, "e": 27901, "s": 27884, "text": "Web Technologies" }, { "code": null, "e": 27999, "s": 27901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28039, "s": 27999, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28100, "s": 28039, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28141, "s": 28100, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28163, "s": 28141, "text": "JavaScript | Promises" }, { "code": null, "e": 28217, "s": 28163, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28257, "s": 28217, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28290, "s": 28257, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28333, "s": 28290, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28383, "s": 28333, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is the difference between break and continue statements in JavaScript?
The break statement is used to exit a loop early, breaking out of the enclosing curly braces. The break statement exits out of a loop. Let’s see an example of break statement in JavaScript. The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace, <html> <body> <script> var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5) { break; // breaks out of loop completely } x = x +1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html> The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise, the control comes out of the loop. The continue statement breaks over one iteration in the loop. This example illustrates the use of a continue statement with a while loop. Notice how to continue statement is used to skip printing when the index held in variable x reaches 8 − <html> <body> <script> var x = 1; document.write("Entering the loop<br /> "); while (x < 10) { x = x+ 1; if (x == 8){ continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html>
[ { "code": null, "e": 1200, "s": 1062, "text": "The break statement is used to exit a loop early, breaking out of the enclosing curly braces. The break statement exits out of a loop. " }, { "code": null, "e": 1475, "s": 1200, "text": "Let’s see an example of break statement in JavaScript. The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace," }, { "code": null, "e": 1870, "s": 1475, "text": "<html>\n <body>\n <script>\n var x = 1;\n document.write(\"Entering the loop<br /> \");\n while (x < 20) {\n if (x == 5) {\n break; // breaks out of loop completely\n }\n x = x +1;\n document.write( x + \"<br />\");\n }\n\n document.write(\"Exiting the loop!<br /> \");\n </script>\n </body>\n</html>" }, { "code": null, "e": 2224, "s": 1870, "text": "The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise, the control comes out of the loop." }, { "code": null, "e": 2466, "s": 2224, "text": "The continue statement breaks over one iteration in the loop. This example illustrates the use of a continue statement with a while loop. Notice how to continue statement is used to skip printing when the index held in variable x reaches 8 −" }, { "code": null, "e": 2858, "s": 2466, "text": "<html>\n <body>\n <script>\n var x = 1;\n document.write(\"Entering the loop<br /> \");\n\n while (x < 10) {\n x = x+ 1;\n if (x == 8){\n continue; // skip rest of the loop body\n }\n document.write( x + \"<br />\");\n }\n document.write(\"Exiting the loop!<br /> \");\n </script>\n </body>\n</html>" } ]